我有这些型号:
产品型号:
protected $fillable = ['id', 'name', 'qty', 'parent_id'];
public function parent() {
return $this->belongsTo(self, 'parent_id');
}
public function children() {
return $this->hasMany(self, 'parent_id');
}
如何获取父产品与其子产品的差异,例如:
产品 1:数量 = 1000;
产品 2:产品 1 的子产品,数量 = 100
产品 3:产品 1 的子产品,数量 = 300
预期查询结果 像这样:
Collection: {
all: [
App\Models\Product: {
id: 1,
qty: 1000,
sum_children: 400,
remaining: 600, // product_1_qty (1000) - sum_children (400)
},...
],
}
我尝试过 withSum 方法,例如:
Product::withSum('children as ttl_children', 'qty') ->addSelect('qty - ttl_chilren');
但是我无法进行这样的计算。
任何人都可以帮助我或指出我正确的方向吗? 谢谢!
由于子项数量的总和是计算出来的,而不是数据库字段,这会阻止您运行原始查询来进行计算。所以我建议对结果使用 laravel 集合方法来达到预期的结果。
$products = Product::whereNull('parent_id')
->withSum('children as sum_children', 'qty')
->get()
->each(
fn($product) => $product->remaining = $product->qty - ($product->sum_children ?? 0)
);
使用这种方法,结果将如下所示,包含
remaining
字段:
Illuminate\Database\Eloquent\Collection {#7265
all: [
App\Models\Product {#7269
id: 1,
name: "ABC",
qty: "1000",
parent_id: null,
created_at: "2024-10-25 13:51:29",
updated_at: "2024-10-25 13:51:29",
sum_children: 400,
remaining: 600,
},
],
}