Home > Net >  Multiple row sum and update
Multiple row sum and update

Time:04-12

I want to update multiple rows while all of them will be summed up with their previous records. For Example, There are 2 products "a" and "b" in a table called "products", they have a column called "quantity". Let's say the product "a" has a quantity of 20 and product "b" has a quantity of 25. Now I am inserting both products' new quantities (the new quantity for product "a" is 5 and 4 for product "b"). The query should update both products' quantity before the insertion, like the quantity of product "a" will be 25 and product "b" will be 29. My codes are :

foreach ($request->product_id as $key => $value) {
    $input['quantity'] = $request->product_quantity[$key];
    $update_stock = Product::update(['id'=>$request->product_id[$key]], 
    $input);
}

CodePudding user response:

You can use the increment here.

Suppose the request array will be,

$productsWithQty = [
    1 => 5,
    2 => 4
];

Where the 1 and 2 is your product ids, product A and B respectively and 5 and 4 is quantities. So query will be,

foreach ($productsWithQty as $product => $qty) {
    Product::findOrFail($product)->increment('quantity', $qty);
}

Try this and let me know the results.

  • Related