How to order by aggregate function results?

114 views Asked by At

How to get result of below tables.

catTbl

catId, name
11     fruit
12     vegetable

prodTbl

pId | catTbl_catId | name
1     11             apple
2     11             orange
3     12             slag

I want to get result for

 cat name     total count
 fruit        2
 vegetable    1

order by with total count--

How to use order by total below cakephp 3 query..

 $cats=$this->catTbl->find()
            ->where(['catTbl.status'=>'1','is_deleted'=>'0'])
            ->select(['name','catId','modified'])          
            ->contain([
            'prodTbl' => function($q) {
              $q->select([
                   'prodTbl.catTbl_catId',
                   'total' => $q->func()->count('prodTbl.catTbl_catId')
              ])
              ->where(['prodTbl.status'=>'1','prodTbl.is_deleted'=>'0'])
              ->group(['prodTbl.catTbl_catId']);

              return $q;
          }
          ]);
1

There are 1 answers

0
shahonseven On

I managed to get the results

+------------+---------+
|    Cat     |  Total  |
+------------+---------+
| fruit      |    2    |
| vegetable  |    1    |
+------------+---------+

using this query

$query = $this->Prod->find();

    $cats = $query->select([
        'Cat.name',
        'total' => $query->func()->count('catId')
    ])
    ->contain([
        'Cat'
    ])
    ->group([
        'catId'
    ])
    ->order([
        'total' => 'DESC'
    ])
    ->all();