jeudi 14 février 2019

How to wrap Eloquent query with parenthesis in Laravel 5.7

I have a query that should load all the posts with just their english translation. If the user enter a keyword it return just the english post with a title containing that keyword.

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')
                ->when($searchKeywords, function ($query, $searchKeywords) {
                    return $query->where('post_translations.title', $searchKeywords)->orWhere('post_translations.title', 'like', '%' . $searchKeywords . '%');
                })
                ->paginate(20);
        }
else
    $posts = Post::select('id', 'title', 'category_id')->orderBy('title')->paginate(20);

The generated query is this one:

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

That return me all the 3 posts translations of the post About. This because of the orWhere. How can I change the eloquent query in order to generate a query like this?

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

The question is not a duplicate of this one because I have one more level of subquery.
How do you wrap Laravel Eloquent ORM query scopes in parentheses when chaining?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire