Skip to content

Commit

Permalink
Merge pull request #27040 from staudenmeir/load-missing
Browse files Browse the repository at this point in the history
[5.7] Fix loadMissing() with duplicate relation names
  • Loading branch information
taylorotwell committed Jan 3, 2019
2 parents e17662b + f5a0560 commit cec4317
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Illuminate/Database/Eloquent/Collection.php
Expand Up @@ -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);
Expand All @@ -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];

Expand Down
14 changes: 14 additions & 0 deletions tests/Integration/Database/EloquentCollectionLoadMissingTest.php
Expand Up @@ -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]);
}
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit cec4317

Please sign in to comment.