You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 09:24:59