Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 729
Phantom Watson Avatar asked Apr 07 '15 19:04

Phantom Watson


1 Answers

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();
like image 166
Phantom Watson Avatar answered Nov 08 '22 08:11

Phantom Watson