laravel - 当我们在 Laravel 5.7 中使用条件子句时如何用括号包装 Eloquent 查询
问题描述
我有一个查询,应该只加载所有帖子的英文翻译。
如果用户输入关键字,它只返回标题包含该关键字的英文帖子。
if ($searchKeywords||$searchCategory){
$posts = Post::
select('post_translations.post_id AS id', 'post_translations.title AS title', 'category_id', 'locale')
->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
->where(‘post_translations.locale','=','en')
->when($searchKeywords, function ($query, $searchKeywords) {
return $query->where('post_translations.title', $searchKeywords)->orWhere('post_translations.title', 'like', '%' . $searchKeywords . '%');
})
->when($searchCategory, function ($query, $searchCategory) {
return $query->where('category_id', '=', $searchCategory);
->paginate(20);
}
else
$posts = Post::select('id', 'title', 'category_id')->orderBy('title')->paginate(20);
生成的查询是这个:
SELECT `post_translations`.`post_id` AS `id`, `post_translations`.`title` AS `title`, `category_id`
FROM `posts` inner join `post_translations`
ON `posts`.`id` = `post_translations`.`post_id`
WHERE `post_translations`.`locale` = 'en'
AND `post_translations`.`title` = 'About'
OR `post_translations`.`title` like 'About’
LIMIT 20 OFFSET 0
这将返回我关于帖子的所有 3 个帖子翻译。
这是因为orWhere。
如何更改 eloquent 查询以生成这样的查询?
SELECT `post_translations`.`post_id` AS `id`, `post_translations`.`title` AS `title`, `category_id`
FROM `posts` inner join `post_translations`
ON `posts`.`id` = `post_translations`.`post_id`
WHERE `post_translations`.`locale` = 'en'
AND (`post_translations`.`title` = ‘About' OR `post_translations`.`title` like 'About’ )
LIMIT 20 OFFSET 0
这个问题不是这个问题的重复,因为我还有一层子查询。
链接时如何将 Laravel Eloquent ORM 查询范围包装在括号中?
解决方案
在 where 查询中添加这两个条件,如下所示:
if ($searchKeywords) {
$posts = Post::select('post_translations.post_id AS id', 'post_translations.title AS title', 'category_id', 'locale')
->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
->where(‘post_translations.locale','=','en')
->where(function ($query) use ($searchKeywords) {
$query->where('post_translations.title', $searchKeywords)
->orWhere('post_translations.title', 'like', '%' . $searchKeywords . '%');
})
->paginate(20);
}
推荐阅读
- python - 如何控制海龟图形窗口的打开和关闭?
- kubernetes - 如何从节点本身检查 Kubernetes 节点的状态?
- java - 如何使用 java 流来避免此代码的突变?
- sql - 如何在 DataGrip 中使用参数运行查询?
- opencv - 从图像中的唯一标识符中检测 ID
- ios - 允许完成处理程序比创建它的本地范围更有效
- nginx - 缓存/保存来自其他域或其他东西的图像(NGINX)
- apache-kafka - 在没有 Confluent Platform 的情况下使用 Apache Kafka 时可以将 Avro 格式用于 KSQL 吗?
- amazon-web-services - 如何将整个文件夹从 s3 存储桶复制到 ec2 实例
- postgresql - 我无法在我的 pgAdmin 中创建新服务器