首页 > 解决方案 > 如何在 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 来完成,但还有其他解决方案吗?

标签: phplaraveleloquenteloquent-relationship

解决方案


您的“请求”看起来像 json,所以首先我们必须使用将其转换为对象或数组json_decode

$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);

推荐阅读