Yii中的数据库请求不好?

我需要从数据库值中选择这样一个请求“select * from prem_message where to_id 12 and del_to 0”? 我编写了这个查询,但它不正确,请通过编写来纠正它:

        $criteria = new CDbCriteria();

        // Select a fields from the database
        $criteria->select='id';
        $criteria->select='from_id';
        $criteria->select='to_id';
        $criteria->select='msg';
        $criteria->select='is_read';
        $criteria->select='from_del';
        $criteria->select='to_del';
        $criteria->select='date';

        // Where to_id == current user id and not delete
        $criteria->condition='to_id=:to';
        $criteria->addCondition('to_del=:del','AND');
        $criteria->params=array(':to'=>Yii::app()->user->id);
        $criteria->params=array(':del'=> 0 );

        $model = Message::model()->findAll($criteria);

错误:

CDbException

CDbCommand无法执行SQL语句:SQLSTATE [HY093]:无效的参数编号:绑定变量的数量与令牌数量不匹配。 执行的SQL语句是:SELECT date FROM prem_message t WHERE(to_id =:to)AND(to_del = del)


它应该被重写为:

    $criteria = new CDbCriteria();

    // Select a fields from the database
    $criteria->select='id, from_id, to_id, msg, is_read, from_del, to_del, date';

    // Where to_id == current user id and not delete
    $criteria->condition='to_id=:to';
    $criteria->addCondition('to_del=:del','AND');
    $criteria->params=array(':to'=>Yii::app()->user->id, ':del'=> 0 );

    $model = Message::model()->findAll($criteria);

这是因为如果您指定了几次变量 - 新值将覆盖所有前一个变量。


你重写params。 这必须解决您的错误:

$criteria = new CDbCriteria();
    // Select a fields from the database
    $criteria->select='id';
    $criteria->select='from_id';
    $criteria->select='to_id';
    $criteria->select='msg';
    $criteria->select='is_read';
    $criteria->select='from_del';
    $criteria->select='to_del';
    $criteria->select='date';

    // Where to_id == current user id and not delete
    $criteria->condition='to_id=:to';
    $criteria->addCondition('to_del=:del','AND');
    $criteria->params=array(
        ':to'=>Yii::app()->user->id),
        ':del'=> 0
    );
    $model = Message::model()->findAll($criteria);
链接地址: http://www.djcxy.com/p/60855.html

上一篇: Bad request to the database in Yii?

下一篇: Yii CDbCommand: getText() with parameters not possible?