13
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP2: virtualFieldを使って集計するときに返ってくる配列をキレイにする

Last updated at Posted at 2016-02-01

やりたいこと

日付ごとにidのレコード数を調べたい.
CakePHP2でfindして,DBからデータを取ってくるときに,count()やsum()などの集計関数を使ってデータを取ろうとすると,以下のようになる.

$result = $this->Model->find('all', array(
	'fields'=> array('id', 'count(id) as cnt'),
	'group' => array('DATE(created)')
));

こうなるとforで回す時などに面倒くさい.

// 返ってくる配列
Array
(
    [0] => Array
        (
            [Model] => Array
                (
                    [id] => 1
                )
            [0] => Array
                (
                    [cnt] => 1  // ココに追加されてしまう。[0]は使いづらい。
                )
        )

解決策

以下のようにすると,使いやすい配列が返る.

$this->Model->virtualFields['cnt'] = 0;	// バーチャルフィールドを追加
$result = $this->Model->find('all', array(
	'fields'=> array('id', 'count(Model.id) as Model__cnt'), // Model__エイリアスにする
	'group' => array('DATE(created)'),
)
);

//使いやすい配列
Array
(
    [0] => Array
        (
            [Model] => Array
                (
                    [id] => 1
                    [cnt] => 1   //Modelの子に入った。
                )

参考

13
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?