Home » Php » php – Update table column with another column values of the same table using updateAll()

php – Update table column with another column values of the same table using updateAll()

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a table that contains these two real fields current and origin.

current value is updated regularly. I want to write a script of reset: for each row I want to put the origin value in the current value.

In MySQL it’s possible with this query:

update MyTable set current = origin

I tried to write this in Yii2 with the query builder:

return $this->updateAll(['current' => 'origin']);

But this doesn’t work because origin is interpreted as string and all rows updated with the value 0.

So how I can update field value by the value of another field using updateAll()?

How to&Answers:

Wrap origin in yii\db\Expression like so:

use yii\db\Expression;

...

return $this->updateAll(['current' => new Expression('origin')]);

and result will be as expected.