问题描述
我正在建立一个论坛.
在主页上,我想显示每个论坛的最新回复.
In the main page, I want to show the last reply for each forum.
层次结构是这样的:
论坛
hasMany('App \ Topic')
hasMany('App\Topic')
hasManyThrough('App \ Topic','App \ Repley')
hasManyThrough('App\Topic', 'App\Repley')
主题
belongsTo('App \ Forum')
belongsTo('App\Forum')
hasMany('App \ Reply')
hasMany('App\Reply')
回复
belongsTo('App \ Topic')
belongsTo('App\Topic')
我这样做了:
$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;
}
推荐答案
我建议的一种解决方案是让答复的 touch
主题. https://laravel.com/docs/5.3/eloquent-relationships#touching-parent-timestamps
One solution I would suggest is to have the replied touch
the topics.https://laravel.com/docs/5.3/eloquent-relationships#touching-parent-timestamps
通过这种方式,您始终可以按主题的 updated_at
进行排序,因为无论何时创建/编辑回复,都会同时更新主题.
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'];
以上假设假设答复模型中主题关系的方法名称为 topic()
.
The above is assuming that the method name for the topics relationship in the replies model is topic()
.
希望这会有所帮助!
这篇关于Laravel排序最后的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!