更新Yii中的查询 [英] Update query in Yii

查看:64
本文介绍了更新Yii中的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Yii中有一项要求,我必须根据某种条件更新一张表.而且我必须用new_val = previous_value + new_val更新该列.但是代码无法按预期运行.

I have one requirement in Yii where I have to update one table based on some condition. And I have to update the column with new_val = previous_value + new_val. But the code is not working as expected.

我尝试的代码是

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

在正常查询中,查询将是

In normal query the query will be

UPDATE tbl_post set star= star + 1,total = total + '$ratingAjax' where id = 1

有人知道哪里出了错吗?

Anybody knows where is mistake?

推荐答案

尝试以下操作:

$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)
    );

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

Using CDbExpression will allow you to send an expression for what to update the column value to be.

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

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

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

这篇关于更新Yii中的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆