Yii (and Yii2) UpdateAll Example

fetchit-21

This is a simple example of how to use Yii’s updateAll():

In this example we want to set status = 1 WHERE type_id = 1 AND status = 0

Note this is a simple example where we are only updating one column and using a string for our condition. There are more complex options available.

Comment::model()->updateAll(array( 'status' => 1 ), 'type_id = 1 AND status = 0' );

So as you can see first comes an array of column => new_value pairs, then a condition string which is pretty much used as the WHERE clause.

An example of updating more than one column:

Comment::model()->updateAll(array( 'status' => 1, 'updated' => '2011-08-25 09:33:23' ), 'type_id = 1 AND status = 0 ' );

Update. Yii2 example:

Updating a single column:

Comment::updateAll(['status' => 1], 'type_id = 1 AND status = 0');

Updating multiple columns:

Comment::updateAll(['status' => 1, 'updated' => '2011-08-25 09:33:23'], 'type_id = 1 AND status = 0' );

3 comments.

  1. Thank you very much!

  2. Hi Harry,

    Can you show an example of how to update ‘One’ Table Column based on condition in ‘Many’ Table Columns.

    Thanks

  3. This post suggests that it’s not possible and you should consider looking into

    Yii::app()->db->createCommand(‘UPDATE …’)->execute();

    http://www.yiiframework.com/forum/index.php/topic/18917-cactiverecordupdateall-using-join-in-where-clause/