Laravel Eloquent Many-to-Many query whereIn

风格不统一 提交于 2019-12-04 18:21:41

问题


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.


回答1:


Use the whereHas() method:

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



回答2:


Try

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


来源:https://stackoverflow.com/questions/42691421/laravel-eloquent-many-to-many-query-wherein

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!