Guy Warner
Laravel & PHP by Guy Warner

Laravel & PHP by Guy Warner

How to fix Integrity constraint violation in Laravel chunkById and lazyById

Photo by David Pupaza on Unsplash

How to fix Integrity constraint violation in Laravel chunkById and lazyById

Guy Warner's photo
Guy Warner
·Jan 28, 2022·

1 min read

When using either chunkById or lazyById with Laravel's query builder you must pass an additional parameter to avoid the error SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "id" is ambiguous.

lazyById:

User::join('posts', 'posts.user_id', 'users.id)
     ->lazyById(100, 'users.id', 'id')
     ->each(function ($user) {
          // do work
     });

chunkById:

User::join('posts', 'posts.user_id', 'users.id)
     ->chunkById(100, function ($user) {
          // do work
     }, 'users.id', 'id')
 
Share this