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
.
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.
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.
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.
Use the whereHas()
method:
$dogs = Dog::whereHas('owners', function($q) use($ownerIds) {
$q->whereIn('id', $ownerIds);
})->get();
Try
$associateDogs = Dog::with(['owners' => function($query) use ($listOfOwners) {
$query->whereIn('id', $listOfOwners);
}])->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With