MySQL Laravel how to multiply by array of values

I have products table which has id, price, name , and I am receiving an array of products id and quantity from front-end, what I want is to calculate the sum of price*quantity.

I know that I can use PHP foreach, but I am looking for database way

//Laravel php way

$sum = 0;
foreach($request->items as $item)
     product = Product::find($item['product_id']);
     $sum += $product->price*$item['quantity']

what I want is to pass the array to mysql and make mysql handle the calculation.

1 answer

  • answered 2021-02-27 17:03

    Do you keep the quantity of the item in the database? If you are happy, you can reach the result you want after a small query, but you need to tell us the details of the structure you have prepared.