Reputation: 147
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.
Upvotes: 2
Views: 4125
Reputation: 520
$query->select(['max_size' => $query->func()->max('size')])
Using SQL Functions- http://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions
Upvotes: 2