【问题标题】:CakePHP 3: How to count and retrieve data for different periods in one query?CakePHP 3:如何在一次查询中统计和检索不同时期的数据?
【发布时间】:2017-10-26 07:30:38
【问题描述】:

我想按DATETIME created字段统计和检索不同时期的数据,例如今天、总计、本周等。

例如 this_week 如何计算?

这里是起始代码:

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

    $query
      ->select([
        'total' => $total,
        //'today' => $today,
        //'this_week' => $this_week,
        //'this_month' => $this_month,
        //'this_year' => $this_year
      ]);

    return $query;
  }

【问题讨论】:

    标签: mysql cakephp orm cakephp-3.0


    【解决方案1】:

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

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

    谢谢

    【讨论】:

    • 您可能需要将其更改为自定义查询。