yii框架search类查询异常,需要分析sql查询语句

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列的出处。

yii入门视频

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值