Search code examples
laraveleloquentlaravel-query-builder

Laravel update chunked result skips rows


I'm trying to convert our database from ID to UUID. When I run the following code to update the database is skips random rows.

AppUser::select('id')->orderBy('created_at')->chunk(1000, function ($appUsers) {
        foreach ($appUsers as $appUser) {
            $uuid = Str::orderedUuid();
            DB::table('files')->where('fileable_type', AppUserInfo::class)->where('fileable_id', $appUser->id)->update([
                'fileable_id' => $uuid
            ]);
            DB::table('app_users')->where('id', $appUser->id)->update(['id' => $uuid]);
        }
    });

Last time i checked ~290 were skipped out of 236196 total.

I've tried to used chunkById, but the same thing happened. The update function is always returning true, so I must assume that Laravel thinks every row is updated when executed.


Solution

  • This is what i ended up doing

    $appUsers = AppUser::select('id')->get();
        $chunkSize = 1000;
        $numberOfChunks = ceil($appUsers->count() / $chunkSize);
        $chunks = $appUsers->split($numberOfChunks);
        
        foreach($chunks as $chunk) {
            foreach($chunk as $appUser) {
                $uuid = Str::orderedUuid();
                DB::table('files')->where('fileable_type', AppUserInfo::class)->where('fileable_id', $appUser->id)->update([
                    'fileable_id' => $uuid
                ]);
                DB::table('app_users')->where('id', $appUser->id)->update(['id' => $uuid]);
            }
        }