From fe61e2d53cc2e2e91d53dc9df90dafef60eb72e2 Mon Sep 17 00:00:00 2001 From: Sergei Tigrov Date: Mon, 27 May 2024 13:12:58 +0700 Subject: [PATCH] Refactor `addInverseRelations()` (#352) --- src/ActiveRelationTrait.php | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/src/ActiveRelationTrait.php b/src/ActiveRelationTrait.php index 07b5df74d..5b30b74fb 100644 --- a/src/ActiveRelationTrait.php +++ b/src/ActiveRelationTrait.php @@ -194,24 +194,21 @@ private function addInverseRelations(array &$result): void return; } - foreach ($result as $i => $relatedModel) { - if ($relatedModel instanceof ActiveRecordInterface) { - if (!isset($inverseRelation)) { - /** @var ActiveQuery $inverseRelation */ - $inverseRelation = $relatedModel->relationQuery($this->inverseOf); - } - $relatedModel->populateRelation( - $this->inverseOf, - $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel - ); - } else { - if (!isset($inverseRelation)) { - /** @var ActiveQuery $inverseRelation */ - $inverseRelation = $this->getARInstance()->relationQuery($this->inverseOf); - } + $relatedModel = reset($result); + + if ($relatedModel instanceof ActiveRecordInterface) { + $inverseRelation = $relatedModel->relationQuery($this->inverseOf); + $primaryModel = $inverseRelation->getMultiple() ? [$this->primaryModel] : $this->primaryModel; + + foreach ($result as $relatedModel) { + $relatedModel->populateRelation($this->inverseOf, $primaryModel); + } + } else { + $inverseRelation = $this->getARInstance()->relationQuery($this->inverseOf); + $primaryModel = $inverseRelation->getMultiple() ? [$this->primaryModel] : $this->primaryModel; - $result[$i][$this->inverseOf] = $inverseRelation->multiple - ? [$this->primaryModel] : $this->primaryModel; + foreach ($result as &$relatedModel) { + $relatedModel[$this->inverseOf] = $primaryModel; } } }