Laravel sorting last record

落爺英雄遲暮 提交于 2021-02-16 15:34:34

问题


I'm bulding a forum.

In the main page, I want to show the last reply for each forum.

The hierarchy is this:

forums

hasMany('App\Topic')

hasManyThrough('App\Topic', 'App\Repley')

topics

belongsTo('App\Forum')

hasMany('App\Reply')

replies

belongsTo('App\Topic')

I did this:

 $forum->replies()->orderBy('created_at', 'desc')->first()

And it worked. But I want to sort by topics and replies. If I post new topic after the last reply, I want that show as the last reply.

Update: I did this, and it work. But is there any other way?

public function last() {
    $topic = $this->topics->sortByDesc('created_at')->first();
    $post = $this->replies->sortByDesc('created_at')->first();

    return ($topic->created_at > $post->created_at) ? $topic : $post;
}

回答1:


One solution I would suggest is to have the replied touch the topics. https://laravel.com/docs/5.3/eloquent-relationships#touching-parent-timestamps

This way you can always order by the Topic's updated_at because whenever a reply is created/edited it will update the Topic as well.

To achieve this you would just need to add:

protected $touches = ['topic'];

The above is assuming that the method name for the topics relationship in the replies model is topic().

Hope this helps!




回答2:


You should have relationships between all of this models. Than you can simply:

$forum->topics->replies->sortByDesc('created_at')->first();

Read more about available methods for collections: https://www.laravel.com/docs/5.2/collections#available-methods




回答3:


You can try this:

$forum->replies()->orderBy('id','DESC')->get();



回答4:


$latestReplay = Replay::orderBy('created_at','desc')->first(); 
$lastTopic = Topic::orderBy('created_at','desc')->first();

    if ($latestReplay->created_at->gt($lastTopic->created_at)) {
          echo $lastReplay->title." is the newer!!"; 
    } else { 
          echo $lastTopic->title." is the newer!";
    }



回答5:


You need to write orignal table name in places of topics and replies in orderBy clause.

  $forum->topics->replies()->orderBy('topics.updated_at','DESC')->orderBy('repliese.updated_at','DESC')->first();


来源:https://stackoverflow.com/questions/39143850/laravel-sorting-last-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!