问题
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