[英]How to Sum Price of Array of Products with their quantities in Laravel
我正在嘗試計算多種產品的價格總和及其數量。 請求是:
[{"product_id": 14, "quantity": 1}, {"product_id": 18, "quantity": 1}, {"product_id": 15, "quantity": 1}]
我從上面的數組中得到 product_ids [14,18,15] 並用 whereIn 找到總和:
Product::whereIn('id', $product_ids)->sum("prices");
在計算總和時如何考慮數量,我可以通過 foreach 來完成,但還有其他解決方案嗎?
您的“請求”看起來像 json 所以首先我們必須使用json_decode
將其轉換為 object 或數組。
$json = '[{"product_id": 14, "quantity": 1}, {"product_id": 18, "quantity": 1}, {"product_id": 15, "quantity": 1}]';
$collection = collect(json_decode($json));
$totalPrice = Product::query()
->select('id', 'price')
->whereIn('id', $collection->pluck('product_id')
->cursor() // we don't really need to load the models in memory.
->reduce(function ($accumulated, $product) use ($collection) { // reduce the collection to a single value
return $accumulated + ( $product->price * $collection->firstWhere('product_id', $product->id)->quantity );
}, 0); // set initial $accumulated is 0
或者使用速記閉包
$totalPrice = Product::query()
->select('id', 'price')
->whereIn('id', $collection->pluck('product_id')
->cursor()
->reduce(fn($a, $p) => $a + ( $p->price * $collection->firstWhere('product_id', $p->id)->quantity ), 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.