danimohamadnejad's avatar

how to update many rows using IDs?

hello. In ecommerce application I want to reduce stock column of products in the cart after order is set. I have a list of product IDs and also qunatity of each one in the cart. so I have an array of Id-quantity pairs: [ ['1','20'], ['2','15'], ... ]

how should I update all products using one query?

0 likes
3 replies
douglasakula's avatar
Level 15

Unless you have a static quantity to update - say items in stock are reducing by a standard 1 item - then you might need to wrap your query within a foreach so that you have the product id and the quantity as variables.

If you have a static quantity cutting across all products to be updated - then you can use SQL IN to update all products stock.

douglasakula's avatar

Sure. You can use eloquent to do that. I would imagine you have a stock model and would need to call it from a controller. Something along this lines.

You would wrap this in a foreach where you are looping through the array of product - quantity array you have product id and quantity would be variable to supply.


DB::table('stock')->where('product_id', $product_id)->decrement('quantity', $quantity);

Above could change based on the way you have implemented your models.

Though again for reporting and history - it might be a better idea to insert a new record or have a stock history table with a history of stock movement. Doing the above erases history of previous stocks. (Unrelated though).

Please or to participate in this conversation.