我正在使用 Laravel 5.4,我有以下关系:
hasMany
线程 ( threads()
) hasMany
发帖 ( posts()
) belongsTo
用户 ( user()
) belongsTo
用户 ( user()
) 目前,在我的
ThreadsController@index
中我有以下几点:public function index()
{
$threads = $this->forum->threads()
->approved()
->withCount(['posts AS approved_replies' => function ($query) {
$query->where('posts.approved', true)->where('posts.is_starting_thread', false);
}])
->with(['posts' => function ($query) { // Posts
$query->approved()
->with('user') // Author of post
->latest();
}]
)
->with('user') // Author of thread
->latest()
->paginate(20);
return view('forums.threads.index')->with([
'forum' => $this->forum, 'threads' => $threads
]);
}
我的
index.blade.php
应该显示 的列表线程 对于每个线程,其中将有:->with('user')
)>withCount(['posts AS approved_replies' => function ($query) { ...
) ->with(['posts' => function ($query) { // Posts
$query->approved()
->with('user') // Author of post
->latest(); // LATEST first
}]
)
... 因为然后在
index.blade.php
我可以通过以下方式访问每个线程的最新帖子:@foreach ($threads as $thread)
{{ $thread->posts->first()->created_at; }}
{{ $thread->posts->first()->user->username; }}
@endforeach
这段代码的问题在于线程是按它们的
created_at
排序的。 ,不是最近的帖子。我想要实现的是按最新(最近的)帖子订购线程,但我不知道如何执行此操作。
最佳答案
这就是我要怎么做。它不是特别漂亮,但应该可以完成这项工作
$this->forum->threads()
->approved()
->join('posts', 'posts.thread_id', '=', 'threads.id')
->selectRaw('threads.*, MAX(posts.created_at) AS latest_post_at')
->groupBy('threads.id')
->orderByDesc('latest_post_at')
->withCount(['posts AS approved_replies' => function ($query) {
$query->where('posts.approved', true)->where('posts.is_starting_thread', false);
}])
->with(['posts' => function ($query) { // Posts
$query->approved()
->with('user') // Author of post
->latest();
}]
)
->with('user')
->paginate(20);
它做了一个
join
正如另一个答案所暗示的那样,然后 groups
通过线程,使用 MAX
聚合函数以保留每组帖子的最新日期。编辑:
$this->forum->threads()
->approved()
->join('posts', 'posts.thread_id', '=', 'threads.id')
->select('threads.*', 'posts.created_at AS latest_post_at')
->whereNotExists(function ($subquery) {
return $subquery->from('posts AS later_posts')
->whereRaw('later_posts.thread_id = posts.thread_id')
->whereRaw('later_posts.created_at > posts.created_at');
})
->orderByDesc('latest_post_at')
->withCount(['posts AS approved_replies' => function ($query) {
$query->where('posts.approved', true)
->where('posts.is_starting_thread', false);
}])
->with(['posts' => function ($query) { // Posts
$query->approved()
->with('user') // Author of post
->latest();
}])
->with('user')
->paginate(20);
关于php - 按最新(最近)相关模型排序 [Laravel],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47965726/