diff --git a/framework/db/Query.php b/framework/db/Query.php index f569339ba5..e8c6438997 100644 --- a/framework/db/Query.php +++ b/framework/db/Query.php @@ -246,13 +246,26 @@ class Query extends Component implements QueryInterface, ExpressionInterface return []; } - if (is_string($this->indexBy) && $this->indexBy && is_array($this->select) && !in_array($this->indexBy, $this->select)) { - if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) { - $this->select[] = key($tables) . '.' . $this->indexBy; - } else { - $this->select[] = $this->indexBy; + if (is_string($this->indexBy) && $this->indexBy && is_array($this->select)) { + $isIndexByAnArray = false; + if (strpos($this->indexBy, '.')) { + $indexByParts = explode('.', $this->indexBy); + foreach ($indexByParts as $indexByPart) { + if (is_numeric($indexByPart)) { + $isIndexByAnArray = true; + break; + } + } + } + if (!$isIndexByAnArray && !in_array($this->indexBy, $this->select, true)) { + if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) { + $this->select[] = key($tables) . '.' . $this->indexBy; + } else { + $this->select[] = $this->indexBy; + } } } + $rows = $this->createCommand($db)->queryAll(); return $this->populate($rows); diff --git a/tests/framework/db/ActiveRecordTest.php b/tests/framework/db/ActiveRecordTest.php index aeb8d9ddca..56f936a0f3 100644 --- a/tests/framework/db/ActiveRecordTest.php +++ b/tests/framework/db/ActiveRecordTest.php @@ -2095,4 +2095,25 @@ abstract class ActiveRecordTest extends DatabaseTestCase } } } + + /** + * @see https://github.com/yiisoft/yii2/issues/18525 + */ + public function testHasManyWithIndexBy() + { + $category = Category::find()->joinWith('items')->indexBy('items.0.name'); + $this->assertEquals(['Agile Web Application Development with Yii1.1 and PHP5', 'Ice Age'], array_keys($category->all())); + + $category = Category::find()->select([Category::tableName() . '.*'])->joinWith('items')->indexBy('items.0.name'); + $this->assertEquals(['Agile Web Application Development with Yii1.1 and PHP5', 'Ice Age'], array_keys($category->all())); + + $category = Category::find()->select([Category::tableName() . '.*'])->joinWith('items')->indexBy('name'); + $this->assertEquals(['Books', 'Movies'], array_keys($category->all())); + + $category = Category::find()->joinWith('items')->indexBy('item.name'); + $this->assertEquals([''], array_keys($category->all())); + + $category = Category::find()->select([Category::tableName() . '.name'])->joinWith('items')->indexBy('id'); + $this->assertEquals([1, 2], array_keys($category->all())); + } }