Search code examples
phplaraveleloquentrelational

Dynamic Query on Relational tables


This is my code:

$query = Book::query();

if (isset($input['alphabet']))
    $query->where('name', 'LIKE', $input['alphabet'] . '%');
if (isset($input['status']))
    $query->where('status', $input['status']);
if (isset($input['genre']))
    $query->with(array('genres' => function($q) use($input) {
        $q->where('genres.id', $input['genre']);
    }));

I want to get all books with name LIKE .... and status = ....
Queries 1 and 2 (name, status) are OK. But the query 3 (genres) is not work.

Book - Genres (Many to many relationship).


Solution

  • If what you are trying to do is to filter and find only the books that belong to a particular genre then

    // Filters and finds only the books that have the particular genre 
    whereHas('genres', function($q) use ($input)
    {
        $q->where('genres.id', '=', $input['genre']));
    
    });
    

    'with' does not put conditions on the books but is used to do eager loading. If you want to filter the books based on whether it belongs to a particular genre then you should be using whereHas and specify the condition inside the anonymous function like above .