dpsfay2510 2014-07-31 13:43
浏览 124
已采纳

如何通过PDO正确获取表的主键作为数组键的数组?

I've done some reading and as of now I know of 3 ways to achieve this.

1: Using PDO::FETCH_KEY_PAIR

Example:

$Query=Yii::app()->db->createCommand('SELECT col1,col2 FROM '.static::tableName().' ORDER BY '.static::tablePrefix().'_id');
$Query->setFetchMode(PDO::FETCH_KEY_PAIR);
return $Query->queryAll();

Which works splendidly, but... only for 2 columns. (BTW, is there a any other way to pass the fetch type? CDbCommand class and its query functions only accept true/false.

2: Using PDO::FETCH_GROUP|PDO::FETCH_ASSOC + array_map('reset', $result)

Example:

$Query=Yii::app()->db->createCommand('SELECT users.user_id,summoners.summoner_name,users.user_login FROM `participants` INNER JOIN `users` ON participant_id=user_id INNER JOIN `summoners` ON user_id=summoner_user_id WHERE participants.tournament_id=1 AND summoners.summoner_region=\'eune\'');
$Query->prepare();
$Query=$Query->getPdoStatement();
$Query->execute();
$Result=$Query->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
return array_map('reset', $Result);

Which is weird, confusing and seems really redundant and ineffective. There is probably some slightly easier way without extracting the statement from Yii's CDbCommand, but still.

3: Using query() + foreach

Example:

$Query=Yii::app()->db->createCommand('SELECT users.user_id,summoners.summoner_name,users.user_login FROM `participants` INNER JOIN `users` ON participant_id=user_id INNER JOIN `summoners` ON user_id=summoner_user_id WHERE participants.tournament_id=1 AND summoners.summoner_region=\'eune\'');
$Data=$Query->query();
foreach ($Data as $row)
    foreach ($row as $k=>$v)
        if($k!='user_id') $Result[$row['user_id']][$k]=$v;
return $Result;

So the 3rd option seems to be the way to go, but don't we have a fetch type for that? I mean... it's 2014, not 1990.

  • 写回答

1条回答 默认 最新

  • drra6593 2014-07-31 15:10
    关注

    No, we don't sadly. If you delve into the ActiveRecord system for Yii to look at how index is setup for relations, you'll find a forrach loop way down in there :-/

    I know because I had the same question and was hoping for the same answer you are looking for ;-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题