你如何在CakePHP 3中使用COUNT(*)和find(' list')?

时间:2015-04-07 19:40:07

标签: php cakephp cakephp-3.0

在CakePHP 3中,我有一个名为文章的模型和一个名为' subject'的字段,我遇到了试图找回100个最常用文章主题列表的障碍。

以下代码生成的SQL选择了所有的可能字段, COUNT(*)

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

然后我记得"CakePHP’s ORM offers abstraction for some commonly used SQL functions."。但是下面的代码导致"错误:函数名称必须是字符串":

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

2 个答案:

答案 0 :(得分:12)

幸运的是,José让我接受了这个伎俩,这就像一个魅力:

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

答案 1 :(得分:-1)

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