Framework: chunk() method is missing half the results

Created on 23 Feb 2018  路  2Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.33
  • PHP Version: 7.1.13
  • Database Driver & Version: Mysql 5.6

Description:

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();
      }                 
   });
}

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.

All 2 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jackmu95 picture jackmu95  路  3Comments

PhiloNL picture PhiloNL  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments

shopblocks picture shopblocks  路  3Comments