CakePHP 3:如何在一个查询中计算和检索不同时期的数据?

时间:2017-10-26 07:30:38

标签: mysql cakephp orm cakephp-3.0

我希望通过 DATETIME 字段计算和检索不同时段的数据,例如今天,总计,本周等。

如何计算例如this_week?

这是开始代码:

this

1 个答案:

答案 0 :(得分:0)

您可以通过执行子查询来实现此目的:

public function findTotalRegistered(Query $query, Array $options)
{
    $total = $query->func()->count('id');

    $query
        ->select([
            'total' => $total,
            'today' => $query->where('DATE(created) = CURDATE()')->count(),
            'this_week' => $query->where('YEARWEEK(DATE(created), 1) = YEARWEEK(CURDATE(), 1))')->count(),
            'this_month' => $query->where('DATE_SUB(NOW(), INTERVAL 1 MONTH)')->count(),
            'this_year' => $query->where('YEAR(created) = YEAR(CURDATE())')->count()
        ])
        ->group(created);

    return $query;
}

由于

相关问题