【问题标题】:Eloquent request : column ID ambiguous雄辩的请求:列 ID 不明确
【发布时间】:2014-09-19 14:18:56
【问题描述】:

我正在尝试使用 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();

有什么帮助吗?

【问题讨论】:

  • 如果表名可能会改变,那么我会采用Product::getTableName() 方法

标签: php laravel eloquent


【解决方案1】:

首先,你不能这样做:

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

【讨论】:

  • 好的。没有什么比这更容易的了?我打算创建一个“getTableName()”函数或将 $table 变量设置为静态。你怎么看?
  • 好吧,如果你觉得它不够简单,并且想为某事创建一个新方法,可以通过内置方法轻松实现,那么我不知道 :)
猜你喜欢
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多