php - 查询 Laravel Eloquent 多对多,其中所有 id 都相等

标签 php laravel eloquent eloquent-relationship

我创建了一个基于 Laravel 的项目,并拥有以下表:companiesattributesattribute_company 相关的多对多关系 attribute_company 用作连接 companiesattributes 表的数据透视表。

我从客户端获得了一组 attribute_id,我需要获得完全具有所有属性的公司的结果。

我找到的唯一解决方案是像这样在内部查询 whereHaswhereIn :

Company::whereHas('attributes', function (Builder $query) use ($atts_ids) {
     $query->whereIn('attribute_id', $atts_ids);
})->get();

如果至少找到一个 attribute_id(这不是我要找的),此查询将返回 companies

如果有人能为我解释得更清楚,那就太好了。

提前谢谢大家:)

最佳答案

一种可能的解决方案:

$company = new Company();
$company = $company->newQuery();

foreach($atts_ids as $att_id)
{
    $company = $company->whereHas('attributes', function (Builder $query) use ($att_id) {
        $query->where('attribute_id', $att_id);
    });
}

$company = $company->get();

关于php - 查询 Laravel Eloquent 多对多,其中所有 id 都相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57766334/

相关文章:

php - Laravel orderBy 关系

Laravel 使用 eloquent 查询多个表

php - 离线更新数据库

javascript - 我真的可以在上传表单中使用这段代码吗?

php - 提供的参数无效 Codeigniter

php - 安装 laravel ( sh : 1: composer: not found) error

laravel - 在 Laravel 应用程序中使用 NPM 包时遇到问题

php - Laravel Eloquent 关系 - 表的多列引用相同的外键

php - MySQL中如何从多个表中获取记录

php - 访问每个用户的所有任务