I have a problem with Laravel's ORM Eloquent chunk() method. It misses some results. Here is a test query :
Model::orderBy('id')->chunk(500, function ($models) {
foreach ($models as $model) {
$model->delete();
}
});
I have 10075 rows in my table and after excuting this code, i still have 5000 rows.
In order to delete all records in my table i use while()
:
while(Model::count() > 0){
Model::orderBy('id')->chunk(500, function ($models) {
foreach ($models as $model) {
$model->delete();
}
});
}
You need to use chunkById instead since you're doing things to the models that affect which pages they end up at.
Imagine a page size of 2, and the models A, B, C, D, E. Doing a chunk will return model A and B, which you delete. Next chunk is page two, which is a skip(2)+take(2), but since you removed A and B you only have C, D and E left. Thus the second chunk will contain E, and you've missed C and D.
Thank you this is was helpful
Most helpful comment
You need to use chunkById instead since you're doing things to the models that affect which pages they end up at.
Imagine a page size of 2, and the models A, B, C, D, E. Doing a chunk will return model A and B, which you delete. Next chunk is page two, which is a skip(2)+take(2), but since you removed A and B you only have C, D and E left. Thus the second chunk will contain E, and you've missed C and D.