Laravel with in with

时间:2021-03-24 11:09:24

标签: php sql laravel orm

我需要计算状态为 X 且物品数量超过一件的人数。

模型:人员、项目、状态

People->items() = belongstomany with item_people table as intermediate    
 
Items->statuses() = belongstomany with item_statuses table as intermediate
People::with(['items','items.statuses' => function ($q){
            $q->whereIn('item_statuses.title', ['X'])
        })
        ->whereHas('items.statuses',function ($q){
            $q->whereIn('statuses.title', ['X'])
        ->withCount('items')->having('items_count','>',1)->get()->count();   

但它确实计算(不应该)没有状态“X”的项目 - 由于预加载 with items,我无法使用 with 过滤掉。

我试过这个,但它不起作用,因为它只在状态内搜索列:

..::with(['items.statuses' => function ($q){
            $q->whereIn('items.item_statuses.title', ['X'])
        })...

我可以在获得查询后通过循环来完成,但我可以这样做吗?

1 个答案:

答案 0 :(得分:0)

你也必须限制你的 withCount :

People::with(['items','items.statuses' => function ($q){
            $q->whereIn('item_statuses.title', ['X'])
        })
        ->whereHas('items.statuses',function ($q){
            $q->whereIn('statuses.title', ['X'])
        ->withCount(['items' => function($q){
$q->whereHas('statuses', function($q){
 $q->whereIn('item_statuses.title', ['X'])
});
}])->having('items_count','>',1)->get()->count();   

现在如果我明白你想做什么:

我需要计算状态为 X 且物品数量超过一件的人数。

那么你应该这样做:

People::whereHas('items', function($query){
            $query->whereHas('statuses', function($query){
                $query->whereIn('item_statuses.title', ['X']);
            });
        }, '>', 1)->count();