简体   繁体   中英

cakephp how do you order by a count field?

I tried the following, but wasn't able to get it to sort.

$options = array(
                         'limit'  => $limit,
                         'offset' => $this->Account->get_offset($page, $limit),
                         'fields' => array(
                                           'Accounts.login', 
                                           'Accounts.name', 
                                           'Accounts.created', 
                                           'COUNT(DISTINCT(Buyer.id)) AS "Accounts__buyer_count"', 
                                           'COUNT(DISTINCT(Seller.id)) AS "Accounts__seller_count"', 
                                           'COUNT(DISTINCT(Certificate.id)) AS "Accounts__certificate_count"'
                                    ),
                         'joins' => array(
                                          array(
                                                'table'      => 'buyers',
                                                'alias'      => 'Buyer',
                                                'type'       => 'LEFT',
                                                'conditions' => array('Buyer.account_id = Accounts.id')
                                          ),
                                          array(
                                                'table'      => 'sellers',
                                                'alias'      => 'Seller',
                                                'type'       => 'LEFT',
                                                'conditions' => array('Seller.buyer_id = Buyer.id')
                                          ),
                                          array(
                                                'table'      => 'certificates',
                                                'alias'      => 'Certificate',
                                                'type'       => 'LEFT',
                                                'conditions' => array('Certificate.buyer_id = Buyer.id')
                                          )
                                    ),
                         'group' => array('Accounts.id'),
                         'order' => array('Accounts__certificate_count' => 'ASC')
        );

Should go to MODEL and add

var $virtualFields = array(
    'buyer_count'       => 'COUNT(DISTINCT(Buyer.id))',
    'seller_count'      => 'COUNT(DISTINCT(Seller.id))',
    'certificate_count' => 'COUNT(DISTINCT(Certificate.id))',
);

After that you can sort the same other fields in table

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