Skip to content

Instantly share code, notes, and snippets.

@tikitikipoo
Created February 18, 2012 15:17
Show Gist options
  • Save tikitikipoo/1859750 to your computer and use it in GitHub Desktop.
Save tikitikipoo/1859750 to your computer and use it in GitHub Desktop.
CakePHPのModel::queryで実行したときの返却結果に嫌悪感抱いたので、強行的な修正を施した
// 嫌悪感を抱いた返却結果
// f,p,gというキーがあるが、これらはテーブルのalias名
array(3) {
[0]=>
array(3) {
["f"]=>
array(3) {
["favorite_id"]=>
string(2) "12"
["picture_id"]=>
string(1) "1"
["twitter_id"]=>
string(6) "999988"
}
["p"]=>
array(1) {
["url"]=>
string(25) "...."
}
["g"]=>
array(1) {
["count"]=>
string(1) "4"
}
}
[1]=>
array(3) {
["f"]=>
array(3) {
["favorite_id"]=>
string(2) "13"
["picture_id"]=>
string(1) "2"
["twitter_id"]=>
string(6) "999988"
}
["p"]=>
array(1) {
["url"]=>
string(25) "...."
}
["g"]=>
array(1) {
["count"]=>
string(1) "3"
}
}
}
// で、今回以下のような返却にした。
array(3) {
[0]=>
array(1) {
[0]=>
array(5) {
["favorite_id"]=>
string(2) "12"
["picture_id"]=>
string(1) "1"
["twitter_id"]=>
string(6) "999988"
["url"]=>
string(25) "...."
["count"]=>
string(1) "4"
}
}
[1]=>
array(1) {
[0]=>
array(5) {
["favorite_id"]=>
string(2) "13"
["picture_id"]=>
string(1) "2"
["twitter_id"]=>
string(6) "999988"
["url"]=>
string(25) "...."
["count"]=>
string(1) "3"
}
}
// 強行突破というか最低な対応ではあるが、CakePHPのコアに追記した。
// lib/Cake/Model/Datasource/Database/Mysql.phpを修正
/**
* Builds a map of the columns contained in a result
*
* @param PDOStatement $results
* @return void
*/
public function resultSet($results) {
$this->map = array();
$numFields = $results->columnCount();
$index = 0;
while ($numFields-- > 0) {
$column = $results->getColumnMeta($index);
if (empty($column['native_type'])) {
$type = ($column['len'] == 1) ? 'boolean' : 'string';
} else {
$type = $column['native_type'];
}
if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
// 独自に追加
// row queryを発行したときにjoinのaliasを
// 配列のキーにして返却しているので
// 自分の処理が面倒になるため以下のように修正
if( $no_alias = Configure::read('noRawQueryAlias') ) {
$this->map[$index++] = array(0, $column['name'], $type);
} else {
$this->map[$index++] = array($column['table'], $column['name
'], $type);
}
} else {
$this->map[$index++] = array(0, $column['name'], $type);
}
}
// 他のクエリに影響が出ないようにfalseにしておく
Configure::write('noRawQueryAlias',false);
}
// 使用する場所で
// デフォルトの結果を返してほしくないときはConfigure::write('noRawQueryAlias',true);を追加。
public function queryFindByTwitterId($params) {
Configure::write('noRawQueryAlias',true);
$sql = ...
$list = $this->query($sql, array($id), false);
// そもそもORM使えよという意見があると思いますが、私が生のSQL派という表現で突っ込みなしの方向で。
// 今回、この稚拙な対応を公開しますが、公開する理由は、もっといい対応が知りたいからです。
// こんな対応有り得ないだろと思ったら是非、アンサーソングならぬアンサーgistやらアンサーブログしてほしいです。
// その他参考にしたサイト
// http://cakephp.jp/modules/newbb/viewtopic.php?topic_id=1098&forum=6
// http://d.hatena.ne.jp/msakamoto-sf/20080221/1203596955
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment