Touhami
Touhami

Reputation: 809

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

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()?

Upvotes: 8

Views: 4032

Answers (1)

arogachev
arogachev

Reputation: 33548

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.

Upvotes: 15

Related Questions