Eloquent request : column ID ambiguous

I’m trying to get all rows of a table with Eloquent where the ID is not in an array $ids.

$product_deleteds = $category->products()->whereNotIn('id', $ids)->get();

I got this error :

SQLSTATE[23000]: Integrity constraint violation: 1052 Column ‘id’ in where clause is ambiguous

The request produce is this one :

Select * 
from `products` 
inner join `products_categories` on `products_categories`.`id` = `products`.`product_category_id` 
where `products`.`deleted_at` is null 
and `products_categories`.`restaurant_id` = 1 
and `id` = 4 limit 1

I know I could make my request like this :
$product_deleteds = $category->products()->whereNotIn('products.id', $ids)->get();

But I don’t want because the name of the table could change. I could to this too, but it seems to be a little tricky :
$product_deleteds = $category->products()->whereNotIn(Product::getTableName().'.id', $ids)->get();

Any help ?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

First off, you couldn’t do that:

$product_deleteds = $category->products()->whereNotIn(
   Product::getTableName() // no such method and definitely not static, unless you create one
.'.id', $ids)->get();

But you can do this in order to avoid hard-coding anything:
$relatedKey = $category->products()->getRelated()->getQualifiedKeyName();

$product_deleteds = $category->products()->whereNotIn($relatedKey, $ids)->get();

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x