Search code examples
phplaravelchunks

Laravel's chunkById ambiguous column


When i use chunkById on a Query Builder with joins, i get the following error:

SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "id" is ambiguous

$query = \DB::table('table1')
            ->select([
                'table1.id'
            ])
            ->join('table2', 'table2.table1_id', '=', 'table1.id')
            ->orderBy('table1.id', 'DESC');

$query->chunkById(1000, function ($items) {
   //do something
});

It works for the first chunk then it throws the error. Is there any way to specify the table of the id that laravel uses to keep track of the chunks?

  • Laravel Version: 5.7.28
  • PHP Version: 7.3.1
  • Database Driver & Version: postgres 10

Solution

  • You need two more parameters:

    $query->chunkById(1000, function ($items) {
       //do something
    }, 'table1.id', 'id');
    

    Read the API doc of Laravel to more details about the third and forth columns: Laravel API doc