This commit is contained in:
Bizley
2021-03-01 21:02:28 +01:00
committed by GitHub
parent 2774f3ea6c
commit 14f1138441
2 changed files with 39 additions and 5 deletions

View File

@@ -246,13 +246,26 @@ class Query extends Component implements QueryInterface, ExpressionInterface
return []; return [];
} }
if (is_string($this->indexBy) && $this->indexBy && is_array($this->select) && !in_array($this->indexBy, $this->select)) { 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) { if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
$this->select[] = key($tables) . '.' . $this->indexBy; $this->select[] = key($tables) . '.' . $this->indexBy;
} else { } else {
$this->select[] = $this->indexBy; $this->select[] = $this->indexBy;
} }
} }
}
$rows = $this->createCommand($db)->queryAll(); $rows = $this->createCommand($db)->queryAll();
return $this->populate($rows); return $this->populate($rows);

View File

@@ -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()));
}
} }