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

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

表达式对象主要用于将原始 SQL 表达式传递给yiidbQuery, yiidbActiveQuery 和相关类的方法。

 

问题:

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

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

Database Exception – yiidbException
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

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!