How do you use COUNT(*) with find('list') in CakePHP 3?

前提是你 提交于 2021-02-18 11:58:51

问题


In CakePHP 3, I had a model called Articles and a field called 'subject', and I ran into a roadblock trying to retrieve a list of the 100 most commonly-used article subjects.

The following code's resulting SQL selected all of the possible fields and not COUNT(*):

$articles->find('list', [
    'keyField' => 'subject',
    'valueField' => 'COUNT(*)'
])
->group('subject')
->order(['COUNT(*)' => 'DESC'])
->limit(100)
->toArray();

Then I remembered "CakePHP’s ORM offers abstraction for some commonly used SQL functions.". But the following code resulted in "Error: Function name must be a string":

$countFunc = $this->find()->func()->count('*');
$articles->find('list', [
    'keyField' => 'subject',
    'valueField' => $countFunc
])
->group('subject')
->order([$countFunc => 'DESC'])
->limit(100)
->toArray();

回答1:


Fortunately, José tipped me off to this trick, which works like a charm:

$articles->find('list', [
    'keyField' => 'subject',
    'valueField' => 'count'
])
->select([
    'subject',
    'count' => $this->find()->func()->count('*')
])
->group('subject')
->order(['count' => 'DESC'])
->limit(100)
->toArray();



回答2:


    $query = $articles->find();
    $query->select(['count' => $query->func()->count('*')]);
    $StaticPages = $query->toArray();
    $StaticPagesCount = $StaticPages[0]->count;


来源:https://stackoverflow.com/questions/29499893/how-do-you-use-count-with-findlist-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!