2013-04-29 118 views
7

我有這個查詢,我想用數量的總和來排序。我已經使用這個結果PAGINATE,請幫助我..如何在cakephp中使用聚合函數SUM?

SELECT (SUM(OrderItem.quantity)) AS qty, `OrderItem`.`item_name` , 
`OrderItem`.`size` FROM `order_items` AS `OrderItem` WHERE 1 =1 
GROUP BY `OrderItem`.`item_name` , `OrderItem`.`size` 
ORDER BY (SUM(OrderItem.quantity)) DESC 

我已經試過代碼波紋管,但它不工作

$this->paginate = array('fields'=>array('(SUM(OrderItem.quantity)) as qty', 
             'OrderItem.item_name', 
            'OrderItem.size'), 
         'group'=>array('OrderItem.item_name','OrderItem.size'), 
         'order' => array('(SUM(OrderItem.quantity))'=>'DESC')); 

回答

4

您可以使用「自定義查詢Pagination¶」跟隨鏈接如下:

http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html#custom-query-pagination

使用此模型中的:

public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) { 
     $page--; 
     $offset=$limit*$page; 
     $result= $this->find('all',array('fields'=>array('(SUM(OrderItem.quantity)) as qty', 
      'OrderItem.item_name', 
      'OrderItem.size'),'group'=>array('OrderItem.item_name','OrderItem.size'),'order' => array('qty'=>'DESC'),'conditions'=>$conditions,'limit'=>$limit, 'offset'=>$offset)); 
     return $result; 

    }