Photo by David Pupaza on Unsplash
How to fix Integrity constraint violation in Laravel chunkById and lazyById
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')