简体   繁体   English

如何在使用数据库功能的Yii中计算查询结果?

[英]How do I count the query results in Yii that uses a database function?

I tried the following 我尝试了以下

// find all keywords that have an uppercase
$upperKeywords = Keyword::find()->where('lower(keyword) != keyword')->orderBy('id');
echo "Found keyword with uppercase: ".$upperKeywords->count().PHP_EOL;
$count = (new Query())->select('count(*)')->from($upperKeywords)->scalar();

The first count attempt gives this error: 第一次计数尝试会出现此错误:

Exception 'yii\db\Exception' with message 'SQLSTATE[42803]: Grouping error: 7 ERROR:  column "keyword.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...FROM "keyword" WHERE lower(keyword) != keyword ORDER BY "id"
                                                                   ^
The SQL being executed was: SELECT COUNT(*) FROM "keyword" WHERE lower(keyword) != keyword ORDER BY "id"'

The second count attempt gives this error: 第二次计数尝试会出现此错误:

PHP Warning 'yii\base\ErrorException' with message 'trim() expects parameter 1 to be string, object given'

in /cygdrive/c/Users/Chloe/workspace/ShopWiz/vendor/yiisoft/yii2/db/Query.php:486

Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'trim() expects ...', '/cygdrive/c/Use...', 486, Array)
#1 /cygdrive/c/Users/Chloe/workspace/ShopWiz/vendor/yiisoft/yii2/db/Query.php(486): trim(Object(yii\db\ActiveQuery))

Shoot, I should have scrolled down more. 射击,我应该向下滚动更多。 This worked. 这工作了。 The array treats it as a subquery and the key value is the table alias. 数组将其视为子查询,并且键值是表别名。

$count = (new Query())->select('count(*)')->from(['t' => $upperKeywords])->scalar();

http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#from http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#from

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM