cakephp你如何通过计数字段订购?

时间:2013-08-23 22:52:23

标签: php sql cakephp orm sql-order-by

我尝试了以下操作,但无法对其进行排序。

$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')
        );

1 个答案:

答案 0 :(得分:0)

应该去MODEL并添加

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

之后,您可以对表

中的其他相同字段进行排序