cakephp find でsql のcount使う方法と注意点

ひとつ前に書いたブログの内容、
sqlのcount使う方法と注意点 - My Note
は、実はCakePHPのfindで実装したかったときにはまった罠でした。
今回は、cakephpのfindでsqlのcount使う方法と注意点を書いていきます。

[ポイント]
cakephpのfindでsqlのcount使う方法と注意点
 →virtual fieldsを追加する必要がある

CakePHPsql のcount使う場合、次のようなプログラムを書きます。

SELECT `device_id`,count(if(`gender_id`=0,1,null)) as count0,count(if(`gender_id`=1,1,null)) as count1 FROM `tables` group by `device_id` order by `device_id`

$this->Table->virtualFields['count0'] = 0;
$this->Table->virtualFields['count1'] = 0;
$tables = $this->Table->find('all', array(
  'fields'=> array('Table.device_id', 'count(if(gender_id=0,1,null)) as Table__count0', 'count(if(gender_id=1,1,null)) as Table__count1'), // エイリアスにする
  'group' => array('Table.device_id'), // GROUP BYのフィールド
   'order' => array('Table.device_id'),
  'recursive' => -1, // int
));

なぜ、virtualFieldsを利用するかというと使用しないとTableのdevice_idと同じ配列に入れないためです。
集計をするためには同じ配列に入っていたほうが良いので、virtualFieldsを利用しました。