S
S
Sergey Gutovsky2018-08-03 01:47:18
Laravel
Sergey Gutovsky, 2018-08-03 01:47:18

How to complete a request?

There is a Person model that is connected to the Genre models through a many-to-many relationship.
In the search query, I need to find people who have all the specified "genres" by the user.
I did it like this

$results = $results->whereHas('genres', function ($query) use ($request){
    $query->whereIn('name', array_column($request->genres, 'name'));
});

But this option returns persons who have at least one of the listed "genres", which is not correct.
How to make it so that the presence of all "genres" of a person is checked.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor, 2018-08-04
@v_decadence

$relations_ids = [1, 2, 3];

Place::whereHas('comforts', function ($query) use ($relations_ids) {
    $query->whereIn('id', $relations_ids);
}, '>=', count($relations_ids))->get();

The point is that the number of records that fall into the desired id is not less than the number of id.
But this only works if one related post cannot be linked multiple times.
Alternatively, you can make a separate whereHas for each id (of course, through a loop so that the code does not copy-paste).
Place::whereHas('comforts', function ($query) use ($relations_ids) {
    $query->whereIn('id', $relations_ids[0]);
})->whereHas('comforts', function ($query) use ($relations_ids) {
    $query->whereIn('id', $relations_ids[1]);
});

I don’t know how fast it all works, I didn’t check it under loads.
The first way, I think, is faster than the second.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question