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

Laravel中如何筛选同时关联item_group_id为0和9的所有Item?

筛选同时拥有item_group_id为0和9的所有Item

关联定义

Item模型中与ItemGroup的多对多关联如下:

public function groups()
{
    return $this->belongsToMany('App\Models\ItemGroup','item_to_group','item_id','item_group_id');
}

原代码的问题

你写的这段代码没法实现需求,原因是with()方法里的闭包只是过滤了关联返回的分组数据,但并不会对Item本身进行筛选——最终会返回所有Item,只是它们关联的groups只保留符合条件的条目而已。

正确实现方案

方案一:子查询实现(对应你给出的SQL逻辑)

直接用Eloquent复刻你提供的SQL:

// 获取符合条件的Item集合
$zeroAndNineItems = \App\Models\Item::whereIn('id', function ($query) {
    $query->select('item_id')
          ->from('item_to_group')
          ->where('item_group_id', 0);
})
->whereHas('groups', function ($query) {
    $query->where('item_group_id', 9);
})
->get();

// 仅统计数量的写法
$zeroAndNineCount = \App\Models\Item::whereIn('id', function ($query) {
    $query->select('item_id')
          ->from('item_to_group')
          ->where('item_group_id', 0);
})
->whereHas('groups', function ($query) {
    $query->where('item_group_id', 9);
})
->count();

方案二:分组+Having筛选(更简洁的写法)

如果item_to_group表中item_id和item_group_id是唯一组合(即一个Item不会重复关联同一个分组),可以用这种方式:

$zeroAndNineCount = \App\Models\Item::whereHas('groups', function ($query) {
    $query->whereIn('item_group_id', [0, 9]);
}, '=', 2)
->count();

逻辑是:先筛选出关联分组包含0或9的Item,再要求这些Item关联的符合条件的分组数量恰好是2——也就是同时属于两个分组。

验证过的原生SQL

你给出的这段SQL可以正确实现需求:

SELECT item_id FROM `item_to_group` WHERE `item_group_id` = 9 AND item_id IN (SELECT item_id FROM `item_to_group` WHERE `item_group_id` = 0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:11:13