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

This commit is contained in:
Brandon Kelly
2019-12-11 15:32:40 -08:00
committed by Alexander Makarov
parent d59c60fac0
commit 88f08005ab
3 changed files with 18 additions and 1 deletions

View File

@ -4,6 +4,7 @@ Yii Framework 2 Change Log
2.0.31 under development 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 #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 #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 cant be bound to `int` and `float` controller action arguments (brandonkelly) - Bug #17701: Throw `BadRequetHttpException` when request params cant be bound to `int` and `float` controller action arguments (brandonkelly)

View File

@ -316,13 +316,21 @@ class Query extends Component implements QueryInterface, ExpressionInterface
} }
$rows = $this->createCommand($db)->queryAll(); $rows = $this->createCommand($db)->queryAll();
$results = []; $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) { foreach ($rows as $row) {
$value = reset($row); $value = reset($row);
if ($this->indexBy instanceof \Closure) { if ($this->indexBy instanceof \Closure) {
$results[call_user_func($this->indexBy, $row)] = $value; $results[call_user_func($this->indexBy, $row)] = $value;
} else { } else {
$results[$row[$this->indexBy]] = $value; $results[$row[$column]] = $value;
} }
} }

View File

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