Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 658
Angelin Calu Avatar asked Mar 09 '17 09:03

Angelin Calu


People also ask

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is chunking in Laravel?

The chunk() method is part of the query builder that fetches data from the database in smaller numbers/amounts. This is suitable when you have thousands of records your application is working with.

What is all () in Laravel?

all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.


2 Answers

Use the whereHas() method:

$dogs = Dog::whereHas('owners', function($q) use($ownerIds) {
    $q->whereIn('id', $ownerIds);
})->get();
like image 178
Alexey Mezenin Avatar answered Sep 22 '22 13:09

Alexey Mezenin


Try

$associateDogs = Dog::with(['owners' => function($query) use ($listOfOwners) {
    $query->whereIn('id', $listOfOwners);
}])->get();
like image 24
EddyTheDove Avatar answered Sep 21 '22 13:09

EddyTheDove