我实现了这种关系,其中仓库属于 ToMany 产品,有很多销售。
我的模型是这样的
仓库.php
public function products () {
return $this->belongsToMany(Product::class)->withPivot('quantity');
}
产品.php
public function sales () {
return $this->hasMany(Sale::class);
}
我想直接从我的 Warehouse 模型访问销售额以对销售额表中的列求和。
我用过 staudenmeir 的 GitHub打包并在我的 Warehouse 模型中添加一个 sales
方法。
public function sales () {
return $this->hasManyDeep(Sale::class, ['product_warehouse', Product::class]);
}
我想做的基本上是对销售表的总列求和,所以我在我的 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"
}
]
这里的问题是,当我向印度仓库添加新销售时,它会为所有仓库返回相同的值。我认为我没有以正确的方式使用 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
表中有 warehouse_id
时,您可以将其作为简单的 hasMany
关系处理并调用 sum
就可以了,
我测试了你的案例并得到了正确的结果,我只是在仓库模型上添加了销售关系:
public function sales()
{
return $this->hasMany(Sale::class);
}
我刚刚做了:
return Warehouse::withSum('sales', 'total')->get();
关于Laravel 有许多深层问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69365175/