Skip to content
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
12 changes: 12 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,18 @@ public function setRelations(array $relations)
return $this;
}

/**
* Enable relationship autoloading for this model.
*
* @return $this
*/
public function withRelationshipAutoloading()
{
$this->newCollection([$this])->withRelationshipAutoloading();

return $this;
}

/**
* Duplicate the instance and unset all the loaded relations.
*
Expand Down
25 changes: 24 additions & 1 deletion tests/Integration/Database/EloquentModelRelationAutoloadTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ protected function afterRefreshingDatabase()
});
}

public function testRelationAutoload()
public function testRelationAutoloadForCollection()
{
$post1 = Post::create();
$comment1 = $post1->comments()->create(['parent_id' => null]);
Expand Down Expand Up @@ -63,6 +63,29 @@ public function testRelationAutoload()
$this->assertTrue($posts[0]->comments[0]->relationLoaded('likes'));
}

public function testRelationAutoloadForSingleModel()
{
$post = Post::create();
$comment1 = $post->comments()->create(['parent_id' => null]);
$comment2 = $post->comments()->create(['parent_id' => $comment1->id]);
$comment2->likes()->create();
$comment2->likes()->create();

DB::enableQueryLog();

$likes = [];

$post->withRelationshipAutoloading();

foreach ($post->comments as $comment) {
$likes = array_merge($likes, $comment->likes->all());
}

$this->assertCount(2, DB::getQueryLog());
$this->assertCount(2, $likes);
$this->assertTrue($post->comments[0]->relationLoaded('likes'));
}

public function testRelationAutoloadVariousNestedMorphRelations()
{
tap(Post::create(), function ($post) {
Expand Down
Loading