在Yii中更新查询

Yog*_*har 8 php mysql yii sql-update

我有一个要求Yii,我必须根据某些条件更新一个表.我必须更新专栏new_val = previous_value + new_val.但是代码没有按预期工作.

我试过的代码是

$update = Yii::app()->db->createCommand()
->update('tbl_post', array('star'=>('star' + 1),'total'=>('total' + $ratingAjax)),
'id=:id',array(':id'=>$post_id));
Run Code Online (Sandbox Code Playgroud)

在正常查询中,查询将是

UPDATE tbl_post set star= star + 1,total = total + '$ratingAjax' where id = 1
Run Code Online (Sandbox Code Playgroud)

谁知道哪里出错了?

Wil*_*ema 19

请尝试以下方法:

$update = Yii::app()->db->createCommand()
    ->update('tbl_post', 
        array(
            'star'=>new CDbExpression('star + 1'),
            'total'=>new CDbExpression('total + :ratingAjax', array(':ratingAjax'=>$ratingAjax))
        ),
        'id=:id',
        array(':id'=>$post_id)
    );
Run Code Online (Sandbox Code Playgroud)

使用CDbExpression将允许您发送表达式以更新列值.

请参阅:http://www.yiiframework.com/doc/api/1.1/CDbCommand#update-detail

和:http: //www.yiiframework.com/doc/api/1.1/CDbExpression# __construct-detail