简体   繁体   中英

Cakephp count containable records

Cakephp 2.6

Schools hasMany Pupils and I am running a containable query from the Schools model. In this query I want to count the number of pupils each school has but I can't get it to work.

I've tried using the following virtual field, but it doesn't work

$this->virtualFields['total'] = 'COUNT(Pupil.id)'; and the following is giving inaccurate counts

$contain = array(
            'Pupil' => array(
                'fields' => array(
                    'CONT(Pupil.id) AS total'
                )
            ),
        );

I don't want to use counterCache as data can be mass imported to both tables outside of the framework so I can't rely on it to update the count field. How can I get this count to run correctly?

Try to add grouping by School s:

    $contain = array(
        'Pupil' => array(
            'fields' => array(
                'CONT(Pupil.id) AS total'
            ),
            'group' => array('Pupil.school_id') // doesn't really know how you called `school` relation column...
        ),
    );

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