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

如何在Laravel中基于多字段条件获取关联分类记录

解决方案

方法一:多条件关联验证(直观版)

针对每个需要的option值,分别验证分类下存在对应的active=1产品,确保所有指定值都被覆盖:

$options = [1, 5, 8];

// 若仅需筛选id=2的分类,直接添加where条件
$categories = Category::where('id', 2)
    ->whereHas('products', fn($query) => $query->where('active', 1)->where('option', 1))
    ->whereHas('products', fn($query) => $query->where('active', 1)->where('option', 5))
    ->whereHas('products', fn($query) => $query->where('active', 1)->where('option', 8))
    ->get();

如果option数组是动态生成的,可通过循环批量添加验证条件:

$options = [1, 5, 8];
$query = Category::where('id', 2);

foreach ($options as $opt) {
    $query->whereHas('products', fn($q) => $q->where('active', 1)->where('option', $opt));
}

$categories = $query->get();

方法二:分组统计验证(高效版)

通过分组统计分类下符合条件的唯一option数量,确保数量等于目标数组长度,以此证明所有值都被覆盖:

$options = [1, 5, 8];
$requiredOptCount = count($options);

$categories = Category::where('id', 2)
    ->whereHas('products', function ($query) use ($options, $requiredOptCount) {
        $query->where('active', 1)
              ->whereIn('option', $options)
              ->groupBy('category_id')
              ->havingRaw('COUNT(DISTINCT option) = ?', [$requiredOptCount]);
    })
    ->get();

两种方法对比

  • 方法一逻辑直观,适合option数量较少的场景;
  • 方法二更适合动态且数量较多的option数组,仅需一次关联查询,性能更优;
  • 两种方案都严格保证:分类关联的产品同时包含所有指定的option值,且对应产品的active状态为1。

内容的提问来源于stack exchange,提问作者Alexey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:50:41