繁体   English   中英

Laravel 雄辩地限制 withCount 与 whereHas 或其他

[英]Laravel eloquent restrict withCount with whereHas or another

我有 3 个模型SupplierPurchasePurchaseDetail 为了通过 Purchase 将供应商模型与 PurchaseDetail 连接起来,我创建了一个 hasManyThrough 关系。

Supplier模型中的hasManyThrough

public function detail_purchases(){
    return $this->hasManyThrough(PurchaseDetail::class, Purchase::class);
}

这种关系运作良好,我可以计算从卖家购买的数量如下:

$collectors = Supplier::withCount(['detail_purchases as qty_sold' => function($query) {
    return $query->select(\DB::raw('SUM(qty)'))
        ->where('unit', '=', 'kg');
}])
    ->where('supplier_type','=','persona_natural')
    ->orderBy('qty_sold','desc')
    ->get();

SQL查询输出:

select `suppliers`.*, (
    select SUM(qty)
    from `purchase_details`
    inner join `purchases` on `purchases`.`id` = `purchase_details`.`purchase_id`
    where `suppliers`.`id` = `purchases`.`supplier_id`
        and `unit` = 'kg'
        and `purchases`.`deleted_at` is null
) as `qty_sold`
from `suppliers`
where `supplier_type` = 'persona_natural'
order by `qty_sold` desc;

输出行:

在此处输入图片说明

我的问题是这个查询给我带来了我没有从他们那里购买的卖家,如果假设 hasManyThrough 关系只加入那些在 Purchase 中注册或从他们那里购买的人,我不知道他们为什么会渗透到查询中.

此外, Supplier模型还有另一个关系称为purchases

public function purchases() {
    return $this->hasMany(Purchase::class, 'supplier_id');
}

模型Purchase有一个 hasMany 和 PurchaseDetail 的关系:

public function details(){
    return $this->hasMany(PurchaseDetail::class, 'purchase_id');
}

在此处输入图片说明

更新

现在使用 whereHas 我可以获得我购买的所有供应商,但是 qty_sold 没有出现在结果中:

$collectors =  Supplier::whereHas('purchases', function($query){
    $query->withCount(['details as qty_sold' => function($query){
        $query->select(\DB::raw('SUM(qty)'))
            ->where('unit', '=', $this->unit);
        }]);
    })
    ->where('supplier_type','=','persona_natural')
    ->get();

这个选择很重要,因为我想知道我购买的所有产品有多少kgs

谢谢@Tony“在您更新的查询中,您可以将 withCount 移出子查询吗?所以您将拥有 Supplier::withCount(...)->whereHas('purchases')..

好的,我修复了它,首先添加whereHas指令,我使用了hasManyThrough关系与withCount 这样,只有有采购的供应商才是选择。

 $collectors =  Supplier::whereHas('purchases')
                                ->withCount([
                                    'detail_purchases as qty_sold' => function($query){
                                        $query->select(\DB::raw('SUM(qty)'))
                                                ->where('unit', '=', 'kg');
                                    }])
                            ->where('supplier_type','=','persona_natural')
                            ->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM