I have been searching everywhere for a solution to this, I hope someone has already solved it or has some good ideas for improvement.
I am using Laravel 5 and I have come accross a situation where I need to update many rows with new values. Right now I’m doing a for-loop for all those rows to update them and I would like to optimize this so that I don’t run many sql queries. Here’s an example code:
<?php //Well, the original code looks better than this, but the concept is the same $myrows = [0,1,2,3,4,5,6,7,8,9]; $myvalues = [45,543,657,574,234,26457,2462,897,234,89032]; for($i=0;$i<count($myrows);$i++) { MyClass::where('id', $myrows[$i])->update(['myColumn' => $myvalues[$i]]); } ?>
Obviously this will execute 10 queries (the same amount as the rows I want to update), but I want to do this with only one query, for optimization purposes. I am aware of the ability to update many rows at the same time with whereIn(…)->update(…) but with this method you can only update all rows to the same value, not different ones like in my example.
Thanks in advance for any help !
Advertisement
Answer
It’s not the matter of Laravel QueryBuilder. If you could do your stuff in one SQL query only, you almost could do it with Laravel.