【问题标题】:How to Sum Price of Array of Products with their quantities in Laravel如何在 Laravel 中将产品数组的价格与其数量相加
【发布时间】:2021-08-03 00:56:13
【问题描述】:

我正在尝试计算多种产品的价格总和及其数量。 请求是:

[{"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 来完成,但还有其他解决方案吗?

【问题讨论】:

  • 将数量乘以 what 肯定不是 product_id
  • 对不起,我编辑了问题,谢谢:)
  • 这需要更多信息。这是特定产品的订单吗?这个 JSON 代表什么?
  • 嗯,这是请求,我正在尝试创建和订购,所以我从请求中获取产品 ID 和数量,我需要计算总和。

标签: php laravel eloquent eloquent-relationship


【解决方案1】:

您的“请求”看起来像 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);

【讨论】:

    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 2018-08-29
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2014-02-05
    相关资源
    最近更新 更多