Yii Framework 2 : Update Query

You can use different type of methods to update the database records in yii2.0 framework. You can use model methods, execute() etc.

save() OR update()

Using model methods, You can load existing record and update the necessary changes in that.

$model = User::find($id);
$model->name = 'YII';
$model->email = '[email protected]';
$model->save();  // equivalent to $model->update();

Update Multiple Records

Using the below methods, You can update the entire table records using given attribute values and condition.
To increment all the users age by 1,

User::updateAllCounters(['age' => 1]);

To change all the users status to active

User::updateAll(['status' => 1], ['like', 'email', '@dummy.com']);

update() command

Instead of writing plain UPDATE query, you can call update() function to change the records. execute() function will complete the update process.


        ->update('table_name', [SET_Values], 'CONDITION')
        ->update('tbl_user', ['status' => 1], 'age > 30')

Update By Sql Query

To run the plain UPDATE query, you can use `createCommand()` function.

$command = $connection->createCommand('UPDATE tbl_user SET status=1 WHERE userid=1');

Leave a Reply

Your email address will not be published. Required fields are marked *