Laravel hasManyDeep 问题

Laravel hasManyDeep issue

我已经实现了这种关系,其中一个仓库 belongsToMany products that has Many sales。

我的模特像

warehouse.php

public function products () {
    return $this->belongsToMany(Product::class)->withPivot('quantity');
}

product.php

public function sales () {
    return $this->hasMany(Sale::class);
}

我想直接从我的 Warehouse 模型访问销售额以对销售额中的列求和 table。

我使用了 staudenmeir 的 GitHub 包并在我的 Warehouse 模型中添加了一个 sales 方法。

public function sales () {
    return $this->hasManyDeep(Sale::class, ['product_warehouse', Product::class]);
}

我想做的基本上是对销售额的总列求和 table 所以我在我的 WarehouseController 中添加了一个 withSum() 方法,就像这样

return Warehouse::query()
        ->withSum('sales', 'total')
        ->get();

结果

[
   {
      "id": 1,
      "warehouse": "Algeria",
      "sales_sum_total": "1000"
   },
   {
      "id": 2,
      "warehouse": "India",
      "sales_sum_total": "1000"
   }
]

这里的问题是,当我向印度仓库添加新销售时,它 returns 所有仓库的值都相同。我认为我没有以正确的方式使用 hasManyDeep() 方法,或者它可能不适用于我的用例。我可以做些什么来让它工作吗?

编辑: 我的数据库结构

    Schema::create('warehouses', function (Blueprint $table) {
        $table->id();
        $table->string('warehouse');
    });

    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->decimal('price');
    });

    Schema::create('product_warehouse', function (Blueprint $table) {
        $table->id();
        $table->foreignId('product_id')->constrained()->cascadeOnDelete();
        $table->foreignId('warehouse_id')->constrained()->cascadeOnDelete();
        $table->integer('quantity')->default(0);
    });

    Schema::create('sales', function (Blueprint $table) {
        $table->id();
        $table->foreignId('warehouse_id')->constrained()->cascadeOnDelete();
        $table->foreignId('product_id')->constrained()->cascadeOnDelete();
        $table->integer('quantity');
        $table->decimal('total');
    });

虽然你在 sales table 中有 warehouse_id 你可以把它当作一个简单的 hasMany 关系来处理,并在它上面调用 sum, 我测试了你的情况并得到了正确的结果,我只是在仓库模型上添加了销售关系:

public function sales()
{
    return $this->hasMany(Sale::class);
}

我刚刚做了:

return Warehouse::withSum('sales', 'total')->get();