How to use aggregate function SUM in cakephp?

I have this query, i want to order by with the sum of quantity. i have to use this result in paginate, Please help me..

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

I have tried the code bellow, but it does not work

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

you can use "Custom Query Pagination¶" follow below link:

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

Use this in your model:

 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;

    }
链接地址: http://www.djcxy.com/p/71180.html

上一篇: CQRS和同步操作(如用户注册)

下一篇: 如何在cakephp中使用聚合函数SUM?