Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

eloquent - 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.

question from:https://stackoverflow.com/questions/65922618/laravel-update-chunked-result-skips-rows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's a big warning in the Laravel documentation on chunking:

When updating or deleting records inside the chunk callback, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the chunked results.

You'll need to find another way to update your keys in batches. I've used the technique described in an answer to this question: How to chunk results from a custom query in Laravel when I could not use the callback required by the chunk method, although in that case it was not for an update query, only a select.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...