Yii Framework 2.0 Update Query

save() OR update()


$model = User::find($id);
$model->name = 'YII';
$model->email = 'yii2@framework.com';
$model->save();  // equivalent to $model->update();

updateAllCounters()


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

update() command

Syntax


$connection	->createCommand()
			->update('table_name', [SET_Values], 'CONDITION')
			->execute();
			
$connection	->createCommand()
			->update('tbl_user', ['status' => 1], 'age > 30')
			->execute();

Update By Sql Query


$command = $connection->createCommand(
		'UPDATE tbl_user SET status=1 WHERE userid=1');
$command->execute();
  • how use UPSERT ?

  • Damianos Giankakis

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

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

  • yatin mistry

    how to update without findOne() ?