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

[5.4] Fix eager load on belongsTo when ID is 0 #17667

Closed
wants to merge 3 commits into from
Closed
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
6 changes: 5 additions & 1 deletion src/Illuminate/Database/Eloquent/Relations/BelongsTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ protected function getEagerModelKeys(array $models)
// execute a "where in" statement to gather up all of those related records.
$keys = collect($models)->map(function ($model) {
return $model->{$this->foreignKey};
})->filter()->all();
})->filter(function ($value) {
return (! is_null($value)) &&
(! is_bool($value) || $value !== false) &&
(! is_string($value) || $value !== '');
})->all();

// If there are no keys that were not null we will just return an array with either
// null or 0 in (depending on if incrementing keys are in use) so the query wont
Expand Down
9 changes: 7 additions & 2 deletions tests/Database/DatabaseEloquentBelongsToTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public function testUpdateMethodRetrievesModelAndUpdates()
public function testEagerConstraintsAreProperlyAdded()
{
$relation = $this->getRelation();
$relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', ['foreign.value', 'foreign.value.two']);
$models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStub, new AnotherEloquentBelongsToModelStub];
$relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', ['foreign.value', 'foreign.value.two', 0]);
$models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStub, new AnotherEloquentBelongsToModelStub, new EloquentBelongsToModelStubWithZeroId];
$relation->addEagerConstraints($models);
}

Expand Down Expand Up @@ -143,6 +143,11 @@ class AnotherEloquentBelongsToModelStub extends \Illuminate\Database\Eloquent\Mo
public $foreign_key = 'foreign.value.two';
}

class EloquentBelongsToModelStubWithZeroId extends \Illuminate\Database\Eloquent\Model
{
public $foreign_key = 0;
}

class MissingEloquentBelongsToModelStub extends \Illuminate\Database\Eloquent\Model
{
public $foreign_key;
Expand Down