Rediska's avatar

How to bulk update records with results from an array?

I have a category table and also a value array that contains the category ID and the number of products in it. This is how I will accomplish my task:

foreach ($tree as $item) {
   Category::find($item['id'])->update(['total_products' => $item['count']]);
}

But this way I get a lot of requests to the database. I think this is the wrong approach. I know there is a massive update:

Category::withTrashed()->update(['total_products' => 15]);

Tell me, is it possible to somehow combine both options? Use bulk update, but substitute values from the array?

0 likes
2 replies
Snapey's avatar

a simple change to halve the transactions is


foreach ($tree as $item) {
   Category::where('id', $item['id'])->update(['total_products' => $item['count']]);
}

Please or to participate in this conversation.