我创建了一个基于 Laravel 的项目,并拥有以下表:companies
、attributes
和 attribute_company
相关的多对多关系 attribute_company
用作连接 companies
和 attributes
表的数据透视表。
我从客户端获得了一组 attribute_id
,我需要获得完全具有所有属性的公司的结果。
我找到的唯一解决方案是像这样在内部查询 whereHas
和 whereIn
:
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/