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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With