Laravel Eloquent Many-to-Many WhereIn Request

In my application, I updated the relationship from one-to-many to many-to-many , and I'm trying to figure out a way to save related functions.

Let's say I have two related tables, for example. dogs and owners. If I have an array of owners and I try to get a list of dog identifiers for these owners, how should I do it eloquently?

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

So, how do I get Dog models where Owner is in an array?

Same as $associatedDogs = Dog::whereIn('owner_id',$ListOfOwners)->get(); for a one-to-many relationship, but for many-to-many .

+7
laravel many-to-many laravel-eloquent
source share
2 answers

Use the whereHas() method:

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

Try

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

All Articles