时间: 2020-09-4|tag:32次围观|0 条评论

 

Yii 官方手册关于 Expression 的解释:https://www.yiichina.com/doc/api/2.0/yii-db-expression

Expression 表示不需要转义或引用的 DB 表达式。
当表达式对象嵌入到 SQL 语句或片段时, 它将替换为 $expression 属性值,而不进行任何的 DB 转义或引用。 例如,
$expression = new Expression('NOW()');
$now = (new \yii\db\Query)->select($expression)->scalar(); // SELECT NOW();
echo $now; // prints the current date

表达式对象主要用于将原始 SQL 表达式传递给yii\db\Query, yii\db\ActiveQuery 和相关类的方法。

 

问题:

当我们需要使用一个常量作为查询字段的时候,使用下面的写法,运行会报错:

User::find()->select(['id', '0 as is_constant'])->asArray()->all()

Database Exception – yii\db\Exception
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list'
The SQL being executed was: SELECT `id`, `0` AS `is_constant` FROM `user`
Error Info: Array
(
[0] => 42S22
[1] => 1054
[2] => Unknown column '0' in 'field list'
)

Caused by: PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list'

 

这时,需要使用 Expression:

User::find()->select(['id', new Expression('0 as is_constant')])->asArray()->all()

 

文章转载于:https://www.cnblogs.com/woods1815/p/12637058.html

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《YII 中使用 Expression解决查询中带有常量报错的问题
   

还没有人抢沙发呢~