-1

I am trying to calculate the sum of the price of multiple products with their quantities. The request is:

[{"product_id": 14, "quantity": 1}, {"product_id": 18, "quantity": 1}, {"product_id": 15, "quantity": 1}]

I get product_ids [14,18,15] from the above array and with whereIn find the sum:

Product::whereIn('id', $product_ids)->sum("prices");

How can I also consider the quantities while calculating the sum, I can do it by foreach but is there any other solution?

Greedy Pointer
  • 334
  • 5
  • 12

1 Answers1

0

Your 'request' looks like json so first we have to transform it to an object or array using 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

Or using shorthand closures

$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);
IGP
  • 14,160
  • 4
  • 26
  • 43