Skip to content

Commit

Permalink
Fix undefined array key errors in ActiveRelationTrait (#221)
Browse files Browse the repository at this point in the history
* Fix undefined array key errors in ActiveRelationTrait
yiisoft/yii2#19158

* styleci
  • Loading branch information
darkdef committed Jan 22, 2023
1 parent af42311 commit 35da084
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/ActiveRelationTrait.php
Expand Up @@ -320,7 +320,12 @@ public function populateRelation(string $name, array &$primaryModels): array
}

foreach ($primaryModels as $i => $primaryModel) {
if ($this->multiple && count($link) === 1 && is_array($keys = $primaryModel[reset($link)])) {
$keys = null;
if ($this->multiple && count($link) === 1) {
$primaryModelKey = reset($link);
$keys = $primaryModel[$primaryModelKey] ?? null;
}
if (is_array($keys)) {
$value = [];
foreach ($keys as $key) {
$key = $this->normalizeModelKey($key);
Expand Down Expand Up @@ -552,7 +557,8 @@ protected function filterByModels(array $models): void
/** single key */
$attribute = reset($this->link);
foreach ($models as $model) {
if (($value = $model[$attribute]) !== null) {
$value = $model[$attribute] ?? null;
if ($value !== null) {
if (is_array($value)) {
$values = array_merge($values, $value);
} elseif ($value instanceof ArrayExpression && $value->getDimension() === 1) {
Expand Down Expand Up @@ -610,7 +616,9 @@ private function getModelKey(ActiveRecordInterface|array $activeRecord, array $a
$key = [];

foreach ($attributes as $attribute) {
$key[] = $this->normalizeModelKey($activeRecord[$attribute]);
if (isset($activeRecord[$attribute])) {
$key[] = $this->normalizeModelKey($activeRecord[$attribute]);
}
}

if (count($key) > 1) {
Expand Down
24 changes: 24 additions & 0 deletions tests/ActiveQueryTest.php
Expand Up @@ -1552,6 +1552,30 @@ public function testPopulateWithoutPk(): void

$this->assertEquals($expected, $aggregation);

// tests with single pk asArray with eager loading
$customerQuery = new ActiveQuery(Customer::class, $this->db);
$aggregation = $customerQuery
->select(['{{customer}}.[[status]]', 'SUM({{order}}.[[total]]) AS [[sumtotal]]'])
->joinWith('ordersPlain')
->groupBy('{{customer}}.[[status]]')
->orderBy('status')
->asArray()
->all();

$expected = [
[
'status' => 1,
'sumtotal' => 183,
'ordersPlain' => [],
],
[
'status' => 2,
'sumtotal' => 0,
'ordersPlain' => [],
],
];
$this->assertEquals($expected, $aggregation);

/** tests with single pk with Models */
$customerQuery = new ActiveQuery(Customer::class, $this->db);
$aggregation = $customerQuery
Expand Down

0 comments on commit 35da084

Please sign in to comment.