【发布时间】:2017-01-06 10:30:33
【问题描述】:
我正在尝试创建一个查询,该查询使用大小写返回列的总和(它记录了时间以及以分钟或小时为单位的格式,如果以小时为单位,则乘以 60 以转换为分钟)。我非常接近,但是查询没有填充CASE 的ELSE 部分。
finder方法是:
public function findWithTotalTime(Query $query, array $options)
{
$conversionCase = $query->newExpr()
->addCase(
$query->newExpr()->add(['Times.time' => 'hours']),
['Times.time*60', 'Times.time'],
['integer', 'integer']
);
return $query->join([
'table' => 'times',
'alias' => 'Times',
'type' => 'LEFT',
'conditions' => 'Times.category_id = Categories.id'
])->select([
'Categories.name',
'total' => $query->func()->sum($conversionCase)
])->group('Categories.name');
}
结果查询是:
SELECT Categories.name AS `Categories__name`, (SUM((CASE WHEN
Times.time = :c0 THEN :c1 END))) AS `total` FROM categories Categories
LEFT JOIN times Times ON Times.category_id = Categories.id GROUP BY
Categories.name
在 CASE 结束之前缺少 ELSE 语句,根据 API 文档:
...the last $value is used as the ELSE value...
https://api.cakephp.org/3.3/class-Cake.Database.Expression.QueryExpression.html
我知道可能有更好的方法来做到这一点,但在这一点上,我至少想知道如何使用内置的 QueryBuilder 正确执行 CASE 语句。
【问题讨论】:
标签: php mysql cakephp cakephp-3.0 cakephp-3.x