如何在Laravel的whereHas中实现多属性关联数据精准筛选?
问题原因
你的查询逻辑是只要变体关联的variant_attributes中存在任意一个attribute_value_id匹配[1,13]中的值,就会被筛选出来:
- 变体2、3的属性包含13,符合条件
- 变体4、7的属性包含1,符合条件
- 只有变体1同时包含1和13,但其他满足单一条件的变体也被纳入了结果,这就是和预期不符的核心原因。
解决方案
你需要的是变体必须同时包含所有指定的attribute_value_id,可以用两种方式实现:
方式1:多次调用whereHas
对每个属性值单独添加whereHas条件,确保变体同时满足所有关联要求:
$attribute_ids = [1, 13]; $variants->where(function ($query) use ($attribute_ids) { foreach ($attribute_ids as $id) { $query->whereHas('variant_attributes', function ($q) use ($id) { $q->where('attribute_value_id', $id); }); } });
方式2:分组统计匹配数
通过whereIn筛选出包含目标值的关联记录,再分组统计匹配的唯一值数量,确保数量等于目标数组的长度:
$attribute_ids = [1, 13]; $count = count($attribute_ids); $variants->whereHas('variant_attributes', function ($q) use ($attribute_ids, $count) { $q->whereIn('attribute_value_id', $attribute_ids) ->groupBy('variant_id') ->havingRaw('COUNT(DISTINCT attribute_value_id) = ?', [$count]); });
注:如果同一个变体的
attribute_value_id不会重复,可以去掉DISTINCT,直接用COUNT(*)。
内容的提问来源于stack exchange,提问作者nashwa ghazy
相关产品推荐
相关产品推荐

