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

[6.x] Override BelongsToMany::cursor() to hydrate pivot relations #30580

Merged
merged 1 commit into from
Nov 13, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,22 @@ public function each(callable $callback, $count = 1000)
});
}

/**
* Get a lazy collection for the given query.
*
* @return \Illuminate\Support\LazyCollection
*/
public function cursor()
{
$this->query->addSelect($this->shouldSelect());

return $this->query->cursor()->map(function ($model) {
$this->hydratePivotRelation([$model]);

return $model;
});
}

/**
* Hydrate the pivot table relationship on the models.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseEloquentIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,18 @@ public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverEachRe
});
}

public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverCursorRequest()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);

foreach (EloquentTestUser::first()->friends()->cursor() as $result) {
$this->assertSame('abigailotwell@gmail.com', $result->email);
$this->assertEquals($user->id, $result->pivot->user_id);
$this->assertEquals($friend->id, $result->pivot->friend_id);
}
}

public function testBasicHasManyEagerLoading()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
Expand Down