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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀