Browse Source

Fix #17687: `Query::indexBy` can now include a table alias

tags/2.0.31
Brandon Kelly 5 years ago committed by Alexander Makarov
parent
commit
88f08005ab
  1. 1
      framework/CHANGELOG.md
  2. 10
      framework/db/Query.php
  3. 8
      tests/framework/db/QueryTest.php

1
framework/CHANGELOG.md

@ -4,6 +4,7 @@ Yii Framework 2 Change Log
2.0.31 under development
------------------------
- Bug #17687: `Query::indexBy` can now include a table alias (brandonkelly)
- Bug #17685: Fix invalid db component in `m180523_151638_rbac_updates_indexes_without_prefix` (rvkulikov)
- Bug #17694: Fixed Error Handler to clear registered view tags, scripts, and files when rendering error view through action view (bizley)
- Bug #17701: Throw `BadRequetHttpException` when request params can’t be bound to `int` and `float` controller action arguments (brandonkelly)

10
framework/db/Query.php

@ -316,13 +316,21 @@ class Query extends Component implements QueryInterface, ExpressionInterface
}
$rows = $this->createCommand($db)->queryAll();
$results = [];
$column = null;
if (is_string($this->indexBy)) {
if (($dotPos = strpos($this->indexBy, '.')) === false) {
$column = $this->indexBy;
} else {
$column = substr($this->indexBy, $dotPos + 1);
}
}
foreach ($rows as $row) {
$value = reset($row);
if ($this->indexBy instanceof \Closure) {
$results[call_user_func($this->indexBy, $row)] = $value;
} else {
$results[$row[$this->indexBy]] = $value;
$results[$row[$column]] = $value;
}
}

8
tests/framework/db/QueryTest.php

@ -391,6 +391,14 @@ abstract class QueryTest extends DatabaseTestCase
->column($db);
$this->assertEquals([3 => 'user3', 2 => 'user2', 1 => 'user1'], $result);
// https://github.com/yiisoft/yii2/issues/17687
$result = (new Query())->from('customer')
->select('name')
->orderBy(['id' => SORT_DESC])
->indexBy('customer.id')
->column($db);
$this->assertEquals([3 => 'user3', 2 => 'user2', 1 => 'user1'], $result);
// https://github.com/yiisoft/yii2/issues/12649
$result = (new Query())->from('customer')
->select(['name', 'id'])

Loading…
Cancel
Save