I have three tables: movies, genres and genre_taggable.
A movie can have one or many genres:
public function genres()
{
return $this->morphToMany(Genre::class, 'genre_taggable', 'genre_taggables', 'genre_id', 'genre_taggable_id');
}
I defined a scope where a user can select multiple genres and get all movies which have one of the selected genres.
public function scopeGenres($query, $genres)
{
return $query->whereHas('genres', function($q) use ($genres){
$q->whereIn('genres.genre_id', $genres);
});
}
Now I wanted to extend the functionality and add the option to show only the movies which have exactly the selected genres, so I thought I just need to concat the genre ids with an AND, like
return $query->whereHas('genres', function($q) use ($genres){
foreach ($genres as $genre) {
$q->where('genres.genre_id', $genre);
}
});
but this doesn't work. I guess that i'm missing something but what? Appreciate any help