简体   繁体   中英

CakePHP 3 Query Builder - How to use max function with a condition?

How can I use max function with a condition?

It's like the following answer in Translate SQL query to CakePHP 3.0 , but in my case I need to use the max function and the case clause (or any other form of condition):

$options['contain'] = array('Users');
$query = $this->Pictures->find('all', $options);
$query->select(['Users.username', 'Users.plan', 'Users.id']);
$query->select(['sum' => $query->func()->sum('size'),])
      ->select(['count' => $query->func()->count('*'),])
      ->select(['facebook' => $query->func()
          ->count('case when type = \'facebook\' then 1 else null end'),])
      ->select(['instagram' => $query->func()
          ->count('case when type = \'instagram\' then 1 else null end'),])
      ->select(['device' => $query->func()
           ->count('case when type = \'device\' then 1 else null end'),])
      ->group('user_id');

return $query;

Thanks for all.

$query->select(['max_size' => $query->func()->max('size')])

使用 SQL 函数- http://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM