A
A
AleDv2020-07-22 20:49:43
Laravel
AleDv, 2020-07-22 20:49:43

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();


In this case, I always get an empty sample. If, instead of the $ids array, only one value is passed, then I get all the films in this genre.

$movies = Movie::with('genres')
            ->whereHas('genres', function ($query) use ($id) {
                    $query->where('genre_movie.genre_id', $id);
            })
            ->get();


If you return an enumeration of all ids, then the result is empty. In this case, the request looks like this:
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` = ?)


I don't understand what's the problem? I must be missing something, please tell me.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2020-07-22
@Fragster

Try replacing the where loop with a single whereIn in the closure.

I
Ilya, 2020-07-22
@New_Horizons

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);

The only thing will come back and films that contain extra. genre. Example:
A movie has 3 genres: Comedy, Drama, Horror, but you need to get films by the Comedy, Horror filter. This movie will also be back. But it seems to me normal behavior for your task?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question