[英]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') hasMany('App \\ Topic')
hasManyThrough('App\\Topic', 'App\\Repley') hasManyThrough('App \\ Topic','App \\ Repley')
topics 主题
belongsTo('App\\Forum') 归属地('App \\ Forum')
hasMany('App\\Reply') hasMany('App \\ Reply')
replies 回覆
belongsTo('App\\Topic') 归属地('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. 我建议的一种解决方案是让答复touch
主题。 https://laravel.com/docs/5.3/eloquent-relationships#touching-parent-timestamps 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. 这样,您始终可以按主题的updated_at
排序,因为无论何时创建/编辑回复,都会同时更新主题。
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()
. 以上假设答复模型中主题关系的方法名称为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 阅读有关可用的收集方法的更多信息: 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!";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.