From f5a05606515fc4f1e2ecb6cc32566f8100d01923 Mon Sep 17 00:00:00 2001 From: Jonas Staudenmeir Date: Thu, 3 Jan 2019 12:23:50 +0100 Subject: [PATCH] Fix loadMissing() with duplicate relation names --- src/Illuminate/Database/Eloquent/Collection.php | 10 +++++++--- .../Database/EloquentCollectionLoadMissingTest.php | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Illuminate/Database/Eloquent/Collection.php b/src/Illuminate/Database/Eloquent/Collection.php index 72d2d8515473..d1405e8d18bc 100755 --- a/src/Illuminate/Database/Eloquent/Collection.php +++ b/src/Illuminate/Database/Eloquent/Collection.php @@ -118,10 +118,14 @@ public function loadMissing($relations) $segments[count($segments) - 1] .= ':'.explode(':', $key)[1]; } - $path = array_combine($segments, $segments); + $path = []; + + foreach ($segments as $segment) { + $path[] = [$segment => $segment]; + } if (is_callable($value)) { - $path[end($segments)] = $value; + $path[count($segments) - 1][end($segments)] = $value; } $this->loadMissingRelation($this, $path); @@ -139,7 +143,7 @@ public function loadMissing($relations) */ protected function loadMissingRelation(Collection $models, array $path) { - $relation = array_splice($path, 0, 1); + $relation = array_shift($path); $name = explode(':', key($relation))[0]; diff --git a/tests/Integration/Database/EloquentCollectionLoadMissingTest.php b/tests/Integration/Database/EloquentCollectionLoadMissingTest.php index db8f5c078dc5..c77527bde97c 100644 --- a/tests/Integration/Database/EloquentCollectionLoadMissingTest.php +++ b/tests/Integration/Database/EloquentCollectionLoadMissingTest.php @@ -43,6 +43,7 @@ public function setUp() Comment::create(['parent_id' => null, 'post_id' => 1]); Comment::create(['parent_id' => 1, 'post_id' => 1]); + Comment::create(['parent_id' => 2, 'post_id' => 1]); Revision::create(['comment_id' => 1]); } @@ -75,6 +76,19 @@ public function testLoadMissingWithClosure() $this->assertTrue($posts[0]->comments[0]->relationLoaded('parent')); $this->assertArrayNotHasKey('post_id', $posts[0]->comments[1]->parent->getAttributes()); } + + public function testLoadMissingWithDuplicateRelationName() + { + $posts = Post::with('comments')->get(); + + DB::enableQueryLog(); + + $posts->loadMissing('comments.parent.parent'); + + $this->assertCount(2, DB::getQueryLog()); + $this->assertTrue($posts[0]->comments[0]->relationLoaded('parent')); + $this->assertTrue($posts[0]->comments[1]->parent->relationLoaded('parent')); + } } class Comment extends Model