使用 updateAll() 将表列更新为同一表的另一个列值


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

我有一个表,其中包含这两个实字段currentorigin

current值会定期更新。我想写一个重置脚本:对于每一行,我想将origin值放在current值中。

MySQL中,可以使用以下查询:

update MyTable set current = origin

我尝试使用查询构建器在 Yii2 中编写它:

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

但这不起作用,因为origin被解释为字符串,并且所有行都更新为值 0

那么如何使用updateAll()通过另一个字段的值更新字段值呢?

origin包装在 yii''db''表达式中,如下所示:

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

结果将符合预期。