CakePHP 3查询生成器 - 如何在条件下使用max函数?

时间:2015-09-26 20:18:20

标签: php mysql cakephp query-builder

如何在条件下使用max函数?

它与Translate SQL query to CakePHP 3.0中的以下答案类似,但在我的情况下,我需要使用max函数和case子句(或任何其他形式的条件):

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

谢谢大家。

1 个答案:

答案 0 :(得分:1)

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

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