Как обернуть Eloquent запрос в круглые скобки, когда мы используем условные предложения в Laravel 5.7 - PullRequest
0 голосов
/ 14 февраля 2019

У меня есть запрос, который должен загружать все сообщения только с их переводом на английский язык.
Если пользователь вводит ключевое слово, он возвращает только сообщение на английском языке с заголовком, содержащим это ключевое слово.

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 поста перевода поста О.
Это из-за или Где .

Как я могу изменить красноречивый запрос, чтобы сгенерировать такой запрос?

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 в скобки при объединении в цепочку?

Ответы [ 2 ]

0 голосов
/ 16 февраля 2019

Я решил с этим кодом:

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')
            ->when($searchKeywords, function ($query, $searchKeywords) {
                return $query->where('post_translations.locale','=','en')
                             ->where(function ($query) use ($searchKeywords) { 
                                  $query->where('post_translations.title', $searchKeywords)->orWhere('post_translations.title', 'like', '%' . $searchKeywords . '%');
                              });

            })
            ->when($searchCategory, function ($query, $searchCategory) {
               return $query->where('post_translations.locale','=','en')
                            ->where(function ($query) use ($searchCategory) { 
                                $query->where('category_id', '=', $searchCategory);
                             });
            })
            ->paginate(20);
}
else
    $posts = Post::select('id', 'title', 'category_id')->orderBy('title')->paginate(20);
0 голосов
/ 14 февраля 2019

Добавьте оба условия внутри запроса 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...