在我的应用程序中,我已经将关系从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?

这里也提出了类似的问题:

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.

推荐答案

Use the whereHas() method:

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

Laravel相关问答推荐

如何判断用户是否已登录Laravel

在Laravel Livewire中,如果一个输入基于另一个唯一的字段是唯一的,如何判断验证?

通过 laravel 中的 url 传递多个字符串作为参数以从数据库中删除特定数据

Laravel 9 上的数组差异助手

如何在自引用表上使用 Laravel 的 hasManyThrough

在 laravel 项目中放置 css 文件的位置

Laravel:如何在 laravel 查询生成器中使用派生表/子查询

将 Laravel 升级到 4.2 后,Artisan::call('migrate') 不起作用

Laravel 5 - 手动分页

Laravel 5在blade中 echo 包含html的会话变量

在 laravel 如何将额外的数据传递给 mutators 和 accessors

Laravel 监听器监听多个事件

在 Laravel 4 迁移中创建 MYSQL 过程

在 Laravel 中将 Public 添加到assets资源路径

如何在 laravel 中解码 Json 对象并在 laravel 中应用 foreach 循环

在 Laravel 中按用户名查找用户

Laravel 邮件密件抄送

如何判断 Laravel 集合是否为空?

Laravel 4:分析器在哪里?

搜索结果分页 laravel 5.3