$deposits = $this->Deposit->find('all', array(
//'fields'=> array('customer_id', "sum(deposit) as sum_deposit"),
'fields'=> array('customer_id', 'SUM(Deposit.deposit) as deposit'),
'group' => array('customer_id'),
));
いろいろ参考サイトから得た情報でやるのだが、以下のようになってしまう。うーん。できるハズなんだがなぁ。
Array ( [0] => Array ( [Deposit] => Array ( [customer_id] => 1 ) [0] => Array ( [deposit] => 200 ) ) [1] => Array ( [Deposit] => Array ( [customer_id] => 2 ) [0] => Array ( [deposit] => 300 ) ) )
これを以下のようにしなければCakePHPらしくない。
スポンサードリンク
Array ( [0] => Array ( [Deposit] => Array ( [customer_id] => 1 [deposit] => 200 ) ) [1] => Array ( [Deposit] => Array ( [customer_id] => 2 [deposit] => 300 ) ) )
/app/app_model.php を設置する
<?php
class AppModel extends Model {
function afterFind($results, $primary=false) {
if($primary == true) {
if(Set::check($results, '0.0')) {
$fieldName = key($results[0][0]);
foreach($results as $key=>$value) {
$results[$key][$this->alias][$fieldName] = $value[0][$fieldName];
unset($results[$key][0]);
}
}
}
return $results;
}
}
?>
参考文献
- Dealing with calculated fields in CakePHP’s find() « nuts and bolts of cakephp :
Dealing with calculated fields in CakePHP’s find()Let’s say we’ve got some calculated field in our find() method, something like SUM() or COUNT() or maybe AVG(). For the ...

コメント
‘fields’=> array(‘customer_id’, ‘SUM(Deposit.deposit) as deposit’
を
‘fields’=> array(‘customer_id’, ‘SUM(Deposit.deposit) as Deposit.deposit’
でうまくいきませんかね?
コメントありがとうございます。
テスト環境が手元にないので、次の機会に試させていただきます。