laravel - Laravel 有很多深层问题
问题描述
我已经实现了这种关系,其中一个仓库属于具有许多销售额的许多产品。
我的模型就像
仓库.php
public function products () {
return $this->belongsToMany(Product::class)->withPivot('quantity');
}
产品.php
public function sales () {
return $this->hasMany(Sale::class);
}
我想直接从我的 Warehouse 模型中访问 sales 以对 sales 表中的一列求和。
我使用了 staudenmeir 的GitHub包并sales
在我的 Warehouse 模型中添加了一个方法。
public function sales () {
return $this->hasManyDeep(Sale::class, ['product_warehouse', Product::class]);
}
我想要做的基本上是汇总销售表的总列,所以我withSum()
在我的 WarehouseController 中添加了一个方法,如下所示
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');
});
解决方案
当您warehouse_id
在sales
表格中时,您可以将其作为一个简单的hasMany
关系处理并调用sum
它,我测试了您的案例并得到了正确的结果,我只是在仓库模型上添加了销售关系:
public function sales()
{
return $this->hasMany(Sale::class);
}
我刚刚做了:
return Warehouse::withSum('sales', 'total')->get();
推荐阅读
- javascript - 如何在不增加网络负担的情况下推送所有待处理的请求?
- matplotlib - Matplotlib 表格大小和位置
- python - Python PIL 文本放置居中
- azure-cosmosdb - 逻辑应用到 CosmosDB - 从文档中提取的 PartitionKey 与标题中指定的不匹配
- amazon-web-services - AWS EC2 IP 更改影响正在运行的作业
- c++ - C++ const char* 弄乱了多重引导标头
- javascript - 为什么我的代码即使在按 ctrl + s(保存)后也不运行?
- python - 如何检测和改变RGB图片中的颜色
- c++ - 如何全局更改向量内的对象c ++
- mysql - 迭代python mysql输出