Kevin
Kevin

Reputation: 1000

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 ?

Upvotes: 0

Views: 1723

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81177

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();

Upvotes: 2

Related Questions