php - 如何在 cakephp 3 中获取最近每小时/每天/每周/每年间隔的总计数?

标签 php mysql cakephp cakephp-3.x

我有一个表格如下-

enter image description here

现在我需要报告每小时、每周、每月和每年的计数总数。它的总和可能为 0,但应包含在结果中。例如我需要如下结果-

$hourlyResult = array(
'00:01' => '5',
'00:02' => '9',
'00:03' => '50',
'00:04' => '5',
..............
..............
'00:55' => '95',
'00:56' => '0',
'00:57' => '20',
'00:58' => '33',
'00:59' => '5',
);

$weeklyResult = array(
'SAT' => '500',
'SUN' => '300'
.............
.............
'FRI' => '700'
);

如何在 cakephp 3 中构建查询?我得到了以下链接,但不能走得太远。

GROUP BY WEEK with SQL

我做了什么-

    $this->loadModel('Searches');   
    $searches = $this->Searches
        ->find('all')
        ->select(['created', 'count'])
        ->where('DATE(Searches.created) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)')
        ->group(WEEK(date))
        ->hydrate(false)
        ->toArray();
    pr($searches);

最佳答案

这里是你如何做到的。

按年求和

    $query = $this->Searches->find();
    $query = $this->Searches
        ->find()
        ->select([
            'total_count' => $query->func()->sum('count'),
            'year' => $query->func()->year(['created' => 'literal'])
        ])
        ->group(['year'])
        ->hydrate(false);

或者

    $query = $this->Searches
        ->find()
        ->select(['total_count' => 'SUM(count)', 'year' => 'YEAR(created)'])
        ->group(['year'])
        ->hydrate(false);

按星期几求和

    $query = $this->Searches->find();
    $query = $this->Searches
        ->find()
        ->select([
            'total_count' => $query->func()->sum('count'),
            'day_of_week' => $query->func()->dayOfWeek('created')
        ])
        ->group(['day_of_week'])
        ->hydrate(false);

或者

    $query = $this->Searches
        ->find()
        ->select(['total_count' => 'SUM(count)', 'day_of_week' => 'DAYOFWEEK(created)'])
        ->group(['day_of_week'])
        ->hydrate(false);

以相同的方式您可以按小时或按月获得总和。 在这里您可以阅读有关 CakePHP > Using SQL Functions 的信息和 date and time functions in MySQL .

关于php - 如何在 cakephp 3 中获取最近每小时/每天/每周/每年间隔的总计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38855851/

相关文章:

php - 在php中动态构建json数组

php - 为什么 php 将空字节添加到私有(private)和 protected 属性名称?

mysql - 无法连接到 MySQL 数据库 - 未指定默认驱动程序

PHP 和 MySQL 问题

Cakephp:在Sql日志中查询后打印注释

php - 带有 IPN 的 Paypal : How to cancel subscription from website,

php - 通过 CLI 运行 PHP 时的 URL 参数

php - Laravel 中按多态关系对数据库结果进行排序

mysql - 为什么 CakePHP 1.3 会自动填充 "Modified"而不是 "Created"字段?

cakephp - 为什么格式化日期会返回错误的年份?