select cakephp 3 中按月分组的记录数

select count of records group by month in cakephp 3

我正在使用 CakePHP 3.x+

我必须在页面上显示图表,因此想为此构建脚本。

我必须 select 按月对当年的记录进行计数。

这是我试过的。

$graph = $this->GenerateVideos->find()
        ->select('COUNT(id)', 'MONTH(created)')
        ->where(['YEAR(created)' => date('Y')])
        ->group(['MONTH(created)']);

产生 sql 喜欢

'sql' => 'SELECT GenerateVideos.COUNT(id) AS GenerateVideos__COUNT(`id`) FROM generate_videos GenerateVideos WHERE YEAR(created) = :c0 GROUP BY MONTH(created) ',
'params' => [
    ':c0' => [
        'value' => '2018',
        'type' => null,
        'placeholder' => 'c0'
    ]
],

但是这是错误的

Error: SQLSTATE[42000]: Syntax error or access violation: 
1064 You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax to use near '(`id`) 
FROM generate_videos GenerateVideos WHERE YEAR(created) = '2018' GROUP BY' at line 1 

尝试在您的 ->select() 值中使用数组:

->select(['COUNT(id)', 'MONTH(created)'])

In the book,它总是显示一个数组,而且似乎没有使用您的第二个 select 值。

或者,根据 the book here,您可以试试这个:

$query = $this->GenerateVideos->find();
$query->select(['count' => $query->func()->count('id'), 'month' => 'MONTH(created)']);
$query->where(['YEAR(created)' => date('Y')])
$query->group(['month' => 'MONTH(created)']);