I would like to be able to somehow mass update an eloquent model without n+1 solutions, lets assume I have a million records here.
First Approach: (bad design)
$users = Users::all(); //1 million record
foreach($users as $user){
$user->age = rand(5, 15);
$user->save();
}
Second Approach: (better a little, still is a n+1 solution)
DB::beginTransaction();
$users = Users::all(); //1 million record
foreach($users as $user){
DB::table('users')
->where('id', '=', $user->id)
->update([
'age' => rand(5, 15),
]);
}
DB::commit();
I personally wish there was a simplified way to do the following:
$users = Users::all(); //1 million record
foreach($users as $user){
$user->age = rand(5, 15);
}
$users->saveAll();
What do you recommend is a better solution that wont end up with 1 million queries? My current solution would be to chunk the records into smaller pieces and throw them in a QUEUE where it will process smaller chunks but, eh.. not sure if that is the proper way to do it either!
DB::raw('update users set age = FLOOR(1 + rand() * 5) where id !='.$user->id);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.