Angelin Calu
Angelin Calu

Reputation: 1915

Laravel Eloquent Many-to-Many query whereIn

In my application I have updated a relationship from one-to-many to many-to-many and I'm trying to figure out a way to persist associated functionality.

Let's say I have two related tables, e.g. dogs and owners. If I have an array of owners and I'm trying to get a list of dogs id's for those owners, how should I do it eloquently?

Similar question was asked here: https://laracasts.com/discuss/channels/laravel/getting-many-to-many-related-data-for-an-array-of-elements

So, How would I get the Dog models where Owner is in an array ?

Same thing as $associatedDogs = Dog::whereIn('owner_id',$ListOfOwners)->get(); is for a One-To-Many relationship, but for Many-to-Many.

Upvotes: 25

Views: 49728

Answers (3)

Davide Casiraghi
Davide Casiraghi

Reputation: 18087

I tried the two suggested solutions but I was getting an error that said that id was not unique. I solved like this:

$dogs = Dog::whereHas('owners', function($q) use($ownerIds) {
    $q->whereIn('owner_id', $ownerIds);
})->get();

Upvotes: 3

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Use the whereHas() method:

$dogs = Dog::whereHas('owners', function($q) use($ownerIds) {
    $q->whereIn('id', $ownerIds);
})->get();

Upvotes: 70

EddyTheDove
EddyTheDove

Reputation: 13259

Try

$associateDogs = Dog::with(['owners' => function($query) use ($listOfOwners) {
    $query->whereIn('id', $listOfOwners);
}])->get();

Upvotes: 2

Related Questions