如何在Yii2中防止SQL中引用列名


How to prevent quoting of column name in SQL in Yii2

我想用Yii2:写这样的SQL

select id, 1 as type from user;

这是我的代码:

$query = User::find()->select(['id', '1 as type'])->all();

1是一个常数,而不是用户的字段

我想将字段type = 1添加到查询结果中。

要在查询的某些部分禁用引用和转义,请将其包装在yii''db''Expression:中

use yii'db'Expression;
...
$query = User::find()->select(['id', new Expresssion('1 as type')])->all();