Eloquent请求:列ID不明确

时间:2014-09-19 14:18:57

标签: php laravel eloquent

我正在尝试使用Eloquent获取表的所有行,其中ID不在数组$ids中。

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

我收到了这个错误:

  

SQLSTATE [23000]:完整性约束违规:1052 where子句中的列'id'不明确

请求产生的是:

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

我知道我可以这样提出要求:

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

但我不想要,因为表的名称可能会改变。我也可以这样做,但似乎有点棘手:

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

任何帮助?

1 个答案:

答案 0 :(得分:2)

首先,你不能这样做:

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

但你可以这样做,以避免硬编码:

$relatedKey = $category->products()->getRelated()->getQualifiedKeyName();

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