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
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Eloquent/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,8 @@ public function loadMissingRelationshipChain(array $tuples)

$this->filter(function ($model) use ($relation, $class) {
return ! is_null($model) &&
! $model->relationLoaded($relation) &&
$model::class === $class;
$model::class === $class &&
! $model->relationLoaded($relation);
})->load($relation);

if (empty($tuples)) {
Expand Down
46 changes: 46 additions & 0 deletions tests/Integration/Database/EloquentModelRelationAutoloadTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;

Expand Down Expand Up @@ -126,6 +127,51 @@ public function testRelationAutoloadWithSerialization()
DB::disableQueryLog();
}

public function testRelationAutoloadChainLoadsModelsOfTheGivenClass()
{
$post = Post::create();
$comment = $post->comments()->create(['parent_id' => null]);
$comment->likes()->create();
$comment->likes()->create();

$posts = Post::get();

$posts->loadMissingRelationshipChain([
['comments', Post::class],
['likes', Comment::class],
]);

$this->assertTrue($posts[0]->relationLoaded('comments'));
$this->assertTrue($posts[0]->comments[0]->relationLoaded('likes'));
$this->assertCount(2, $posts[0]->comments[0]->likes);
}

public function testRelationAutoloadChainSkipsNonModelRelationValues()
{
$post = Post::create();
$comment = $post->comments()->create(['parent_id' => null]);
$comment->likes()->create();

$posts = Post::get();

// A relation is not required to hold a model or a collection of models.
// Packages such as Lighthouse put a paginator there to represent a paginated relation.
foreach ($posts as $each) {
$each->setRelation('comments', new LengthAwarePaginator($each->comments()->get(), 1, 10));
}

$posts->loadMissingRelationshipChain([
['comments', Post::class],
['likes', Comment::class],
]);

$paginator = $posts[0]->getRelation('comments');

// The paginator is left as it was found rather than being loaded into.
$this->assertInstanceOf(LengthAwarePaginator::class, $paginator);
$this->assertFalse($paginator->items()[0]->relationLoaded('likes'));
}

public function testRelationAutoloadWithCircularRelations()
{
$post = Post::create();
Expand Down
Loading