How to combine multiple WHERE condidtions in WITH and WHEREHAS in Laravel Eloquent query

137 Views Asked by At

In below query the awarded, banned, featured and published parts are being ignored, why?

Query: Show me a list of all featured published books with an author that has been awarded and has not been banned.

$books = myBooks::with('authors')
            ->whereHas('authors', function ($query) {
                $query
                    ->where([
                        'awarded' => true,
                        'banned' => false
                    ]);
            })
            ->where([
                'featured' => true,
                'published' => true
            ])
            ->latest()
            ->get();
2

There are 2 best solutions below

0
Vlad On

Most likely some of these fields: awarded, banned, featured and published are present in both of your tables. For the query to work correctly in the conditions you need to specify the ownership of these fields

$books = Books::with('authors')
    ->whereHas('authors', function ($query) {
        $query
            ->where([
                'authors.awarded' => true,
                'authors.banned' => false,
            ]);
    })
    ->where([
        'books.featured' => true,
        'books.published' => true,
    ])
    ->latest()
    ->get();
1
apokryfos On

I don't see the syntax you are using documented anywhere. You can try doing:

$books = myBooks::with('authors')
            ->whereHas('authors', function ($query) {
                $query
                    ->where([
                        [ 'awarded', '=', true ],
                        [ 'banned',  '=', false ]
                    ]);
            })
            ->where([
                [ 'featured', '=', true ],
                [ 'published', '=', true ]
            ])
            ->latest()
            ->get();