Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update query in Yii

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.

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?

like image 540
Yogesh Suthar Avatar asked Mar 26 '13 16:03

Yogesh Suthar


3 Answers

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 CDbExpression will allow you to send an expression for what to update the column value to be.

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

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

like image 76
Willem Renzema Avatar answered Oct 05 '22 22:10

Willem Renzema


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));
like image 26
Philippe Boissonneault Avatar answered Oct 05 '22 20:10

Philippe Boissonneault


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

like image 21
apoq Avatar answered Oct 05 '22 22:10

apoq