cakePHPでmysqlのCOUNT
cakePHPでmysqlのCOUNT(*)の処理をする際に
下記のように配列が望んでいる形で返ってこない場合の対処
(※cakePHP1.2系)
$f = array("COUNT(`Model`.`field`) as `count_result`,"field_1","field_2");
array(1) {
[0]=>
array(2) {
[0]=>
array(1) {
["count_result"]=>
string(1) "0"
}
["Model"]=>
array(3) {
["field_1"]=>
NULL
["field_2"]=>
NULL
}
}
}
\\cake\libs\model\datasources\dbo_source.php
<?php function fetchResult() { if ($row = mysql_fetch_row($this->results)) { $resultRow = array(); $i = 0; foreach ($row as $index => $field) { list($table, $column) = $this->map[$index]; $resultRow[$table][$column] = $row[$index]; $i++; } return $resultRow; } else { return false; } } ?>
\\cake\libs\model\datasources\dbo_source.php
<?php function fetchResult() { if ($row = mysql_fetch_row($this->results)) { $resultRow = array(); $i = 0; # editer a9b $t_table = 0; foreach ($row as $index => $field) { list($table, $column) = $this->map[$index]; # editer a9b if(empty($table)){ $table = $t_table; }else{ $t_table = $table; } $resultRow[$table][$column] = $row[$index]; $i++; } return $resultRow; } else { return false; } } ?>
また、上記の修正ではフィールド指定の順序を持ってきたいフィールドの後ろに置かないと動きません。
$f = array("field_1","field_2","COUNT(`Model`.`field`) as `count_result`");
array(1) {
[0]=>
array(1) {
["Model"]=>
array(4) {
["field_1"]=>
NULL
["field_2"]=>
NULL
["count_result"]=>
string(1) "0"
}
}
}