Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'status' in where clause is ambiguous
The SQL being executed was: SELECT COUNT(*) FROM `comment` INNER JOIN `user` ON comment.userid = user.id WHERE `status`='1'
Error Info: Array
(
[0] => 23000
[1] => 1052
[2] => Column 'status' in where clause is ambiguous
)
↵
Caused by: PDOException
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'status' in where clause is ambiguous
in C:\wamp64\www\advanced\vendor\yiisoft\yii2\db\Command.php at line 1293
学习魏曦yii入门视频5.1节,按照视频敲代码,中间遇到一个错误,查询评论状态出错。错误发生在新增作者查询后:
public function search($params)
{
$query = Comment::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'status' => $this->status,
'create_time' => $this->create_time,
'userid' => $this->userid,
'post_id' => $this->post_id,
'remind' => $this->remind,
]);
$query->andFilterWhere(['like', 'content', $this->content])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'url', $this->url]);
//新增代码的位置:
$query->join('INNER JOIN', 'user','comment.userid = user.id');
$query->andFilterWhere(['like','user.username',$this->getAttribute('user.username')]);
$dataProvider->sort->attributes['user.username']=
[
'asc'=>['user.username'=>SORT_ASC],
'desc'=>['user.username'=>SORT_DESC],
];
return $dataProvider;
}
检查数据库发现,当表join连接后,合并的表有两个status列,一个来自comment表,一个来自user表:
所以产生混淆:Column ‘status’ in where clause is ambiguous
解决这个问题,需要改下自动生成的搜索函数(下面代码的第三行):
将’status’ => $this->status,改为’comment.status’ => $this->status,
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'comment.status' => $this->status,
'create_time' => $this->create_time,
'userid' => $this->userid,
'post_id' => $this->post_id,
'remind' => $this->remind,
]);
标明status列的出处。