Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.7] Fix loadMissing() with duplicate relation names #27040

Merged
merged 1 commit into from
Jan 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/Illuminate/Database/Eloquent/Collection.php
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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