laravel - 带有条件语句的 Laravel Eager Load
问题描述
今天是个好日子
我是 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”(最新的)排序评论?
提前致谢
解决方案
您当前的方法看起来很适合按喜欢计数排序结果,如果没有喜欢,您仍然可以通过添加另一个带有created_at
列的 order by 子句来获得最新记录
$news = News::with([
'thumbnail',
'source',
'comments' => function ($query) {
$query->withCount('likes');
$query->orderBy('likes_count', 'DESC')
->orderBy('created_at', 'DESC');
}
])->paginate(5);
从最初的评论复制
因此,如果所有评论都有 0 个赞,那么最新的评论将首先出现在列表中,如果评论有赞,那么它们也将首先按赞数排序,然后按创建时间排序。
一旦您订购了集合,然后当您循环您的新闻记录时,然后从您的相关记录中选择第一项
推荐阅读
- c++ - 如何创建一个在文本中找到匹配单词的函数,包括跳过
- gulp - gulpfile 错误 AssertionError [ERR_ASSERTION]: 必须指定任务函数
- spring-boot - 创建名为“rabbitTemplate”的 bean 时出错 - 使用 Spring Boot 的 CloudAMQP
- sql - 在一个公共列上连接三个表
- vue.js - Vue Cli 应用程序在部署到 heroku 时失败“错误:无法解析 vue-axios”
- python - 如何使用 len 计算行数
- android - 如何连接另一个表的总和
- pycharm - 在 PyCharm 中显示文档
- c - Execvp(argv[1], argv),不返回这样的文件或目录
- java - 给定无效的base64编码字符串,如何使Android Base64.decode可靠抛出异常(或返回null)?