简体   繁体   中英

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();

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();
    $query = $articles->find();
    $query->select(['count' => $query->func()->count('*')]);
    $StaticPages = $query->toArray();
    $StaticPagesCount = $StaticPages[0]->count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM