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 = 'yii2@framework.com';
$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');

  • how use UPSERT ?

  • Damianos Giankakis

    can i update 2 tables (or more) at the same time?

    $connection ->createCommand()
    ->update(‘tbl_user’, [‘status’ => 1], ‘age > 30’)
    ->update(‘tbl_products’, [‘userid’ => null], ‘userid > $some_param)

  • yatin mistry

    how to update without findOne() ?
    $model = User::find($id);
    $model->name = ‘YII’;
    $model->email = ‘yii2@framework.com’;
    Above code will execute two so want to update in one query

  • Ahmad AL-Zahabi

    if I use update() command, how to make it return the number of rows that convenient with the condition (even if any update occurs)