首页 > 解决方案 > 当我们在 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 查询范围包装在括号中?

标签: laravellaravel-5eloquent

解决方案


在 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);
}

推荐阅读