6

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
Petru Lebada
  • 2,167
  • 8
  • 38
  • 59

1 Answers1

15

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

Hieu Le
  • 8,288
  • 1
  • 34
  • 55
  • Broken link. Found some form of older documentation [here](https://docs1.w3cub.com/laravel~5.2/api/5.2/illuminate/database/eloquent/builder/#method_chunkById) – Karin Aug 12 '20 at 11:22
  • 1
    Previous link is also broken, try this: https://laravel.com/api/8.x/Illuminate/Database/Concerns/BuildsQueries.html#method_chunkById – Sithell Oct 26 '21 at 17:52