今天是个好日子
我是 Laravel 的新手,目前正在用它构建我的第一个简单的新闻应用程序
我有一个简单的查询,使用 laravel 的急切加载功能但是在这个急切加载功能中,我想根据某些条件获取某些评论
例子:
use App\News;
...
public function home() {
$news = News::with([
'thumbnail',
'source', // link to real news source
'comments' => function ($query) {
// fetch a comment where likes > 0, otherwise, get latest comment
// *get only one*
}
])->paginate(5);
return response()->json([
'news' => $news
]);
}
这个怎么做?
更新
我找到了一种按点赞数排序评论的方法,但如果每条评论中都没有点赞,我不知道如何通过“created_at”(获取最新评论)对评论进行排序
我需要包含“likes_count” withCount('likes')
,然后按降序排列
public function home() {
$news = News::with([
'thumbnail',
'source',
'comments' => function ($query) {
$query->withCount('likes');
$query->orderBy('likes_count', 'DESC')->first();
// return the first comment that has likes or most liked comment
}
])->paginate(5);
...
}
现在,如果评论中没有赞,如何将后备查询按“created_at”(最新的)排序评论?
提前致谢