Cakephp COUNT per month per year

How do you use cakephp to count, for example, the number of posts made each month in a year?

It is preferable to use Model-> find ('count') and get the data in an array.

+3
source share
3 answers

It's close

Query

$data = $this->Post->query("SELECT COUNT(id),MONTH(created) FROM posts GROUP BY YEAR(created), MONTH(created);");

Return

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [COUNT(id)] => 1
                    [MONTH(created)] => 3
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [COUNT(id)] => 2
                    [MONTH(created)] => 4
                )

        )

)
+1
source

I just did something similar using CakePHP only (no direct requests). It works in CakePHP 2, not tested in 1.x.

The code for your example would be something like this:

$params = array(
  'recursive' => -1,
  'fields' => array('id', 'MONTH(created)')
  'group' => array('YEAR(created)', 'MONTH(created)')
);

$numberOfPosts = $this->Model->find('count', $params);
+4
source

. , , , .

1: ( ): , , .

2: use the query as mentioned earlier, but put it in the model class and not in the application class.

0
source

Source: https://habr.com/ru/post/1741499/


All Articles