Skip to content

Commit

Permalink
Fix morphTo eager loading
Browse files Browse the repository at this point in the history
  • Loading branch information
acasar committed Jun 30, 2016
1 parent a8df2de commit ee7b8cf
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ public function getRelation($name)
* @param string $relation
* @return array
*/
public function nestedRelations($relation)
protected function nestedRelations($relation)
{
$nested = [];

Expand Down
6 changes: 3 additions & 3 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -828,11 +828,11 @@ public function morphTo($name = null, $type = null, $id = null)
list($type, $id) = $this->getMorphs($name, $type, $id);

// If the type value is null it is probably safe to assume we're eager loading
// the relationship. When that is the case we will pass in a dummy query as
// there are multiple types in the morph and we can't use single queries.
// the relationship. In this case we'll just pass in a dummy query where we
// need to remove any eager loads that may already be defined on a model.
if (empty($class = $this->$type)) {
return new MorphTo(
$this->newQuery(), $this, $id, null, $type, $name
$this->newQuery()->setEagerLoads([]), $this, $id, null, $type, $name
);
}

Expand Down
4 changes: 1 addition & 3 deletions src/Illuminate/Database/Eloquent/Relations/MorphTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,9 @@ protected function getResultsByType($type)

$key = $instance->getTable().'.'.$instance->getKeyName();

$eagerLoads = $this->getQuery()->nestedRelations($this->relation);

$query = $this->replayMacros($instance->newQuery())
->mergeModelDefinedRelationConstraints($this->getQuery())
->with($eagerLoads);
->with($this->getQuery()->getEagerLoads());

return $query->whereIn($key, $this->gatherKeysByType($type)->all())->get();
}
Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseEloquentPolymorphicIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,18 @@ public function testItLoadsNestedRelationshipsAutomatically()
$this->assertEquals(TestUser::first(), $like->likeable->owner);
}

public function testItLoadsNestedRelationshipsOnDemand()
{
$this->seedData();

$like = TestLike::with('likeable.owner')->first();

$this->assertTrue($like->relationLoaded('likeable'));
$this->assertTrue($like->likeable->relationLoaded('owner'));

$this->assertEquals(TestUser::first(), $like->likeable->owner);
}

/**
* Helpers...
*/
Expand Down

0 comments on commit ee7b8cf

Please sign in to comment.