我有两个桌子。第一个是产品,第二个是类别。它们包含具有相同名称的字段-“名称”。 在模型产品中,我添加了以下代码:
public function getCategory(){
return $this->hasOne(Category::className(), ['id' => 'cat_id']);
}
我需要在GridView中显示表Category中的列。我在ProductSearch模型中为此添加了以下代码:
$query->joinWith(['category' => function($query) { $query->from(['cat' => 'category']); }]);
此代码为表Category添加别名cat。
那之后我得到一个错误:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'name' in where clause is ambiguous
The SQL being executed was: SELECT COUNT(*) FROM `product` LEFT JOIN `category` `cat` ON `product`.`cat_id` = `cat`.`id` WHERE `name` LIKE '%aasdadadsdgdgdg%'
Error Info: Array
(
[0] => 23000
[1] => 1052
[2] => Column 'name' in where clause is ambiguous
)
如何为表Product添加别名?
答案 0 :(得分:0)
打开您的ProductSearch
模型,导航到search($params)
方法。在下面,您应该看到过滤部分:
$query->andFilterWhere(['like', 'name', $this->name])
通过将表名称product
写入该行来修复歧义部分。
$query->andFilterWhere(['like', 'product.name', $this->name])
或..
$query->andFilterWhere(['like', self::tableName() . '.name', $this->name])
这将提供准确的信息,该名称应从product.name
表中查询。
有趣的是,只有加入Category
表之后,您才会收到错误消息。
Imho,最糟糕的是发现此错误,因为看起来一切正常,直到使用搜索功能为止。