Laravel Eloquent 多对多查询 whereIn

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42691421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:31:18  来源:igfitidea点击:

Laravel Eloquent Many-to-Many query whereIn

laravelmany-to-manylaravel-eloquent

提问by Angelin Calu

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

在我的应用程序中,我已经更新了从one-to-many到的关系,many-to-many并且我正在尝试找出一种方法来保留相关的功能。

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?

假设我有两个相关的表,例如狗和所有者。如果我有一群主人,而我正在尝试为这些主人获取狗的 ID 列表,我应该如何雄辩地做到这一点?

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

这里问了类似的问题:https: //laracasts.com/discuss/channels/laravel/getting-many-to-many-related-data-for-an-array-of-elements

So, How would I get the Dogmodels where Owneris in an array ?

那么,我将如何获得数组中的Dog模型Owner

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

同样的事情,$associatedDogs = Dog::whereIn('owner_id',$ListOfOwners)->get();是一个One-To-Many关系,但对Many-to-Many

回答by Alexey Mezenin

Use the whereHas()method:

使用whereHas()方法:

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

回答by EddyTheDove

Try

尝试

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