php Yii 中的更新查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15641947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:40:55  来源:igfitidea点击:

Update query in Yii

phpmysqlyiisql-update

提问by Yogesh Suthar

I have one requirement in Yiiwhere 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.

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

The code I tried is

我试过的代码是

$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?

有谁知道错误在哪里?

回答by Willem Renzema

Try the following:

请尝试以下操作:

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

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

使用CDbExpression将允许您发送一个表达式来更新列值。

See: http://www.yiiframework.com/doc/api/1.1/CDbCommand#update-detail

见:http: //www.yiiframework.com/doc/api/1.1/CDbCommand#update-detail

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

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

回答by Philippe Boissonneault

Your working with strings, try this :

你使用字符串,试试这个:

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

回答by apoq

This should do the job:

这应该可以完成这项工作:

   Post::model()->updateCounters(
        array('star'=>1),
        array('total'=>$ratingAjax),
        array('condition' => "id = :id"),
        array(':id' => $post_id),
    );

It will increment, not set the values

它将递增,而不是设置值