3

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.

Terax
  • 130
  • 5
  • possible duplicate of [Is there a way to fetch associative array grouped by the values of a specified column with PDO?](http://stackoverflow.com/questions/5361716/is-there-a-way-to-fetch-associative-array-grouped-by-the-values-of-a-specified-c) – Félix Adriyel Gagnon-Grenier Aug 01 '14 at 01:56

1 Answers1

1

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 ;-)

acorncom
  • 5,975
  • 1
  • 19
  • 31
  • you are wrong. it is possible by using this: `->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE)` with the second method in the question – Félix Adriyel Gagnon-Grenier Aug 01 '14 at 20:10
  • @FélixGagnon-Grenier Thanks and sure enough :-) Looks like it can get a bit tricky though: http://blog.ulf-wendel.de/2008/is-pdofetch_unique-broken-by-design/ – acorncom Aug 02 '14 at 20:05