Toggle Database Field

How to execute this query in Yii

UPDATE 'users' AS 'User' SET 'User'.'status' = 1 -'User'.'status' WHERE 'User'.'id' = 1

if a field is 0 or 1, then

update table set field = 1 - field

Users::model()->updateAll('your parameters');

or if you haven’t a model:

Yii::app()->db->createCommand('your SQL);


I have tryed these, and non of them worked

Yii::app()->db->createCommand('UPDATE `users` SET `users`.`status` = 1 -`users`.`status` WHERE `users`.`id` = 1');

User::model()->updateAll(array('status'=> '1 - `User.status`'),'id = '.$id );

$command = Yii::app()->db->createCommand();

$command->update('users', array(


), 'id=:id', array(':id'=>$id));

and some variations of them

Isn’t there any strict varian of duing this with Yii

[size=2]for ex…[/size]

Model1: UpdateByPk?



                      ($Model->id,array("status"=>'ok'));   ?>

Model2: updateAll?






[size=2]and how to make “‘User’.‘status’ = 1 -‘User’.‘status’”[/size]

status have only 2 states (zero, one)

This should be worked:


                          $id,//primary key you want to update





I guess zero and one are the only possible states for "status", then make constants for "status" and use them in your code.


                          $id,//primary key you want to update







And I would like to create toggle action which every time will change the state of ‘status’ field depending on the previous value. The main think in my question is How To use the current value of a field while updating. Example of the required query is in the topic



Constantinff, if you do this: users.status = 1 -users.status, what happen if “status” is zero? It’ll be worth -1, and only 1 and 0 are correct,right?

You could rewrite beforeUpdate() method in your model, checking that if $model->status is 0, then you change it for 1 and conversely.


[size=2]1 - 0 = 1[/size]



Even so you could rewrite beforeUpdate() method for to automate this.

:-[ :-X :-[ :-X :-[ :-X

Yii::app()->db->createCommand('UPDATE `users` SET `users`.`status` = 1 -`users`.`status` WHERE `users`.`id` = 1')->execute();

This one works properly, but how to make it as component/extension or something else that will be easily reusable for other controllers

But each model has your controller, then why do you want to reuse this code in another controllers????

In each model you should write the code used by its controller.

So I tell you to rewrite beforeUpdate function (in each model, of course).


and thats why I need to make the ‘users’ and ‘status’ fields variables