本文介紹了Laravel用一個(gè)條件計(jì)算兩列之和的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我有一個(gè)從數(shù)據(jù)庫(kù)中獲得的倉(cāng)庫(kù)集合
[
{
"id": 1,
"warehouse": "India"
"sales": [
{
"id": 1,
"warehouse_id": 1,
"price": "120.00",
"quantity": 1000,
"status": 1
},
{
"id": 2,
"warehouse_id": 1,
"price": "20.00",
"quantity": 100,
"status": 1
},
{
"id": 3,
"warehouse_id": 1,
"price": "40.00",
"quantity": 1000,
"status": 2
}
]
},
{
"id": 2,
"warehouse": "Malaysia"
"sales": [
{
"id": 4,
"warehouse_id": 2,
"price": "160.00",
"quantity": 100,
"status": 1
}
]
}
]
我想計(jì)算每個(gè)倉(cāng)庫(kù)的總收入
總收入根據(jù)銷(xiāo)售額status
屬性計(jì)算
如果Status=1,則產(chǎn)品已交付,因此應(yīng)將price * quantity
添加到總收入
如果status=2,則返回產(chǎn)品,因此應(yīng)從總收入中減去price * quantity
印度倉(cāng)庫(kù)基本示例:
total_income = 120*1000 + 20*100 - 40*1000
馬來(lái)西亞:
total_income = 160*100
我嘗試使用Warehouse::withSum();
,但沒(méi)有任何效果。
我想知道有沒(méi)有收藏的好辦法
推薦答案
您只需向集合的sum()
方法傳遞幾個(gè)回調(diào):
$warehouses_collection->map(function ($warehouse) {
return (object) [
'id' => $warehouse->id,
'warehouse' => $warehouse->warehouse,
'total_income' => collect($warehouse->sales)->sum(function ($sale) {
((int) $sale->price) * $sale->quantity * ($sale->status == 1 ? 1 : -1)
})
];
});
WithSum
在這里使用有點(diǎn)麻煩,但調(diào)用withAggregate
可以。
Warehouse::withAggregate(
'sales as total_income',
'sum(case when status = 1 then price * quantity when status = 2 then price * quantity * -1 else 0 end)'
)->get()
這篇關(guān)于Laravel用一個(gè)條件計(jì)算兩列之和的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,