0

我有下一个数据库:

在此处输入图像描述

因此我有三个 php 模型PurchaseSupplier并且PurchaseDetail. 我的模型Supplier与:hasManyPurchase

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

该模型Purchase与 有hasMany关系PurchaseDetail

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

从这里开始,关系没有问题。当我尝试获取每个供应商所有采购的总数量时,问题就来了。我做了下一个查询:

$collectionCenters = Supplier::whereHas('purchases', function($q1){
                    $q1->whereHas('details', function($q2){
                        $q2->select(\DB::raw('SUM(qty) as purchasesQtyKg'))
                        ->where('unit', 'kg');
                    });
            })->where('supplier_type','=','juridic_person')
            ->get();

从 laravel 调试栏输出查询:

select * from `suppliers` where exists (select * from `purchases` where `suppliers`.`id` = `purchases`.`supplier_id` and exists (select SUM(qty) as purchasQtyKg from `purchase_details` where `purchases`.`id` = `purchase_details`.`purchase_id` and `unit` = 'kg') and `purchases`.`deleted_at` is null) and `supplier_type` = 'juridic_person'

如您所见,我正在使用与 whereHas 指令的关系。但是什么也没发生,它只抛出了我数据库的三个供应商,但带有别名的列purchasesQtyKg没有出现在结果中:

在此处输入图像描述

查询的 Phpmyadmin 输出:

在此处输入图像描述

我也做了这样的事情:

 $collectionCenters = Supplier::where('supplier_type','=','juridic_person')
                            ->with(['purchases.details' => function($query){
                                $query->select(\DB::raw("SUM(purchase_details.qty) as purchaseQtyKg"))
                                ->where('unit', $this->unit);
                            }])->get();

但是什么都没有发生,恐怕因为这应该有效。我会感谢任何想法的人来解决这个问题。非常感谢。

4

2 回答 2

1

whereHas不会更改结果集(它只是限制结果)。 https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

你可以在 laravel 8 中使用这样的东西

withSumhttps ://laravel.com/docs/8.x/eloquent-relationships#other-aggregate-functions

$collectionCenters = Supplier::query()
    ->whereHas('purchases', function ($q1) {
        $q1->whereHas('details', function ($q2) {
            $q2->where('unit', 'kg');
        });
    })
    ->with([
        'purchases' => function ($query) {
            return $query->withSum('details', 'qty')->where('unit', 'kg');
        }
    ])
    ->where('supplier_type', '=', 'juridic_person')
    ->get();
于 2021-11-10T03:42:07.267 回答
1

我修复了在模型中创建hasManyThrough关系的问题:Supplier

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

然后使用 Eloquent 我可以使用这种关系:

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

输出:

#attributes: array:9 [▼
        "id" => 4
        "supplier_type" => "persona_juridica"
        "department_id" => 14
        "province_id" => 1403
        "district_id" => 140308
        "community_id" => null
        "created_at" => "2021-11-04 09:55:49"
        "updated_at" => "2021-11-04 09:55:49"
        "purchaseQtys" => "6"

我还创建了魔术方法或属性:

   public function getQtySoldKgAttribute(){
        return  $this->detail_purchases()->where('unit','kg')->sum('qty');
   
   }
   public function getQtySoldTonsAttribute(){
        return $this->detail_purchases()->where('unit','t')->sum('qty');
  }

  public function getQtySoldGramsAttribute(){
    return $this->detail_purchases()->where('unit','g')->sum('qty');
 }
 public function getQtySoldGallonsAttribute(){
    return $this->detail_purchases()->where('unit','gal')->sum('qty');
 }
 public function getQtySoldLitersAttribute(){
    return $this->detail_purchases()->where('unit','l')->sum('qty');
 }
 public function getQtySoldMillilitersAttribute(){
    return $this->detail_purchases()->where('unit','ml')->sum('qty');
 }

当您使用 sum firt 时,我们需要添加 where 条件,然后sum添加指令,如果您先添加 thesum再添加 thewhere它将不起作用。

干杯!。

于 2021-11-11T20:35:09.403 回答