Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'));
like image 220
ARJUN KP Avatar asked Apr 29 '13 04:04

ARJUN KP


1 Answers

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;

    }
like image 98
Pank Avatar answered Sep 27 '22 19:09

Pank