Skip to content

Commit

Permalink
[11.x] Bugfix for calling pluck() on chaperoned relations. (#52680)
Browse files Browse the repository at this point in the history
* Added failing test for hydrating inverse relations

This test should fail if non-models are passed to
`applyInverseRelationToCollection()`, e.g. when
`pluck()` is called on a query.

* Only attempt inverse hydration on models.
  • Loading branch information
samlev authored Sep 6, 2024
1 parent bb670ae commit caec234
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ protected function applyInverseRelationToCollection($models, ?Model $parent = nu
$parent ??= $this->getParent();

foreach ($models as $model) {
$this->applyInverseRelationToModel($model, $parent);
$model instanceof Model && $this->applyInverseRelationToModel($model, $parent);
}

return $models;
Expand Down
26 changes: 26 additions & 0 deletions tests/Database/DatabaseEloquentInverseRelationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,27 @@ public function testSetsGuessedInverseRelationBasedOnForeignKey()
$this->assertSame('test', $relation->getInverseRelationship());
}

public function testOnlyHydratesInverseRelationOnModels()
{
$relation = m::mock(HasInverseRelationStub::class)->shouldAllowMockingProtectedMethods()->makePartial();
$relation->shouldReceive('getParent')->andReturn(new HasInverseRelationParentStub);
$relation->shouldReceive('applyInverseRelationToModel')->times(6);
$relation->exposeApplyInverseRelationToCollection([
new HasInverseRelationRelatedStub(),
12345,
new HasInverseRelationRelatedStub(),
new HasInverseRelationRelatedStub(),
Model::class,
new HasInverseRelationRelatedStub(),
true,
[],
new HasInverseRelationRelatedStub(),
'foo',
new class() {},
new HasInverseRelationRelatedStub(),
]);
}

public static function guessedParentRelationsDataProvider()
{
yield ['hasInverseRelationParentStub'];
Expand Down Expand Up @@ -361,4 +382,9 @@ public function exposeGuessInverseRelation(): string|null
{
return $this->guessInverseRelation();
}

public function exposeApplyInverseRelationToCollection($models, ?Model $parent = null)
{
return $this->applyInverseRelationToCollection($models, $parent);
}
}

0 comments on commit caec234

Please sign in to comment.