简体   繁体   中英

Laravel sorting last record

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;
}

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!

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

您可以尝试以下方法:

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

您需要在orderBy子句中的主题和答复处写入原始表名。

  $forum->topics->replies()->orderBy('topics.updated_at','DESC')->orderBy('repliese.updated_at','DESC')->first();
$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!";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM