【问题标题】:select count of records group by month in cakephp 3在cakephp 3中按月选择记录数
【发布时间】:2018-02-22 06:12:28
【问题描述】:

我正在使用CakePHP 3.x+

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

我必须按月选择当年的记录数。

这是我尝试过的。

$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 

【问题讨论】:

标签: cakephp cakephp-3.x


【解决方案1】:

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

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

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

或者,根据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)']);

【讨论】:

  • 我尝试了下面的脚本,但它给出的错误为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
  • 生成的脚本显示为SELECT (COUNT(id)) AS count, GenerateVideos.MONTH(created) AS GenerateVideos__MONTH(created) FROM generate_videos GenerateVideos WHERE YEAR(created) = :c0 GROUP BY MONTH(created)
  • 知道了,将MONTH(created) 更改为'month' => 'MONTH(created)' 正在工作
猜你喜欢
  • 2015-05-30
  • 2013-05-21
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多