Answer the question
In order to leave comments, you need to log in
How to get in Eloquent the main model by the condition in the relationship?
Hello. There are two models Movies (Movie) and Genres (Genre). Movies are related to genres by a belongsToMany relationship with the genre_movie pivot table.
Task: find all movies with given genre id.
I do it like this:
$movies = Movie::with('genres')
->whereHas('genres', function ($query) use ($ids) {
foreach ($ids as $id) {
$query->where('genre_movie.genre_id', $id);
}
})
->get();
$movies = Movie::with('genres')
->whereHas('genres', function ($query) use ($id) {
$query->where('genre_movie.genre_id', $id);
})
->get();
select * from `movies` where exists (select * from `genres` inner join `genre_movie` on `genres`.`id` = `genre_movie`.`genre_id` where `movies`.`id` = `genre_movie`.`movie_id` and `genre_movie`.`genre_id` = ? and `genre_movie`.`genre_id` = ?)
Answer the question
In order to leave comments, you need to log in
Try replacing the where loop with a single whereIn in the closure.
Not sure, but try this:
$genresIds = [1, 2];
$movies = Movie::whereHas('genres', function ($q) use ($genresIds) {
$q->whereIn('id', $genresIds);
}, '=', count($genresIds))
->get();
dd($movies);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question