4

I'm using CakePHP 3.x+

I have to show a graph on the page and thus want to build script for that.

I have to select count of records group by month for current year.

This is what I have tried.

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

which generates sql like

'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'
    ]
],

But this is giving error as

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 
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285
  • Possible duplicate of [Cakephp 3 : How to get max amout row from a table](https://stackoverflow.com/questions/37850117/cakephp-3-how-to-get-max-amout-row-from-a-table) – arilia Feb 22 '18 at 11:18

1 Answers1

5

Try using an array in your ->select() value:

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

In the book, it always shows an array, and it doesn't appear to be utilizing your second select value.

Or, per the book here, you could try this:

$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)']);
Dave
  • 28,833
  • 23
  • 113
  • 183
  • I tried below script, but it is giving error as `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 '(`created`) FROM generate_videos GenerateVideos WHERE YEAR(created) = '2018' GRO' at line 1` – Anuj TBE Feb 23 '18 at 04:31
  • the generated script showing is `SELECT (COUNT(id)) AS `count`, GenerateVideos.MONTH(created) AS GenerateVideos__MONTH(`created`) FROM generate_videos GenerateVideos WHERE YEAR(created) = :c0 GROUP BY MONTH(created) ` – Anuj TBE Feb 23 '18 at 04:35
  • 1
    Got it, changing `MONTH(created)` to `'month' => 'MONTH(created)'` is working – Anuj TBE Feb 23 '18 at 04:54