Laravel排序最后一个记录


Laravel sorting last record

我正在建立一个论坛。

在主页面,我想显示每个论坛的最后回复。

层次结构如下:

论坛

hasMany (App '主题)

hasManyThrough("App '主题","App ' Repley")

belongsTo (App '论坛)

hasMany (App '回复)

belongsTo (App '主题)

我这样做了:

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

它起作用了。但我想按主题和回复排序。如果我在最后一个回复之后发布新主题,我希望该节目作为最后一个回复。

:我这么做了,而且很有效。但还有别的办法吗?

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

我建议的一个解决方案是让回复的touch成为主题。https://laravel.com/docs/5.3/eloquent-relationships touching-parent-timestamps

这样,您就可以始终按照主题的updated_at进行排序,因为每当创建/编辑回复时,它也会更新主题。

要达到这个目的,你只需要添加:
protected $touches = ['topic'];

以上假设回复模型中主题关系的方法名为topic()

希望这对你有帮助!

您应该拥有所有这些模型之间的关系。那么你可以简单地:

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

阅读更多关于集合的可用方法:https://www.laravel.com/docs/5.2/collections#available-methods

你可以试试:

$forum->replies()->orderBy('id','DESC')->get();
$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!";
    }

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

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