What does the other query look like?
Mode::each() with 100,000 records, issues on updating
Hi,
I have a query that fetches around 100,000 records. I need o update certain records based on certain criteria:
MyModel::where('is_paid', false)->count();
// Result: 100,000
// This should loop trough all the 100,000 records
MyModel::where('is_paid', false)->each(function($model){
if($model->total === 0) { // Total is an accesor property that triggers a query itself.
$model->is_paid = true;
$model->save();
}
});
MyModel::where('is_paid', true)->count();
// Result: 45,000
// Expected: 70,000
You would expect that all records that meet the condition "total === 0", would be updated, right? Unfortunately not. For some weird reason, probably memory related, some models are skipped. The reason might be that the missed records are simply not fetched at all, or they hit the loop but the save() is not doing the job.
If I run the same query a second time, and then check the affected models, the result would be something like: 46,000 (a thousand more). That means that the second run found models that weren't affected on the first run.
If I keep running the same query over and over again, the affected records keep increasing, till finally all records are updated as expected (70, 000 records).
I'd like to know if there are some obvious issues here, if it's related to the number of records I'm fetching, and what would be the safest way to do it without having to run multiple times the same query.
By the way, I already tried with chunks of 1000 records, but the problem still around.
Using MySQL 8.
Thanks.
Please or to participate in this conversation.