skip to Main Content

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

Answers


  1. 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();
    
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search