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 BelongsTo not accepting id == 0 in foreign relations #17668

Merged
merged 1 commit into from
Jan 30, 2017
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
10 changes: 7 additions & 3 deletions src/Illuminate/Database/Eloquent/Relations/BelongsTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,16 @@ public function addEagerConstraints(array $models)
*/
protected function getEagerModelKeys(array $models)
{
$keys = [];

// First we need to gather all of the keys from the parent models so we know what
// to query for via the eager loading query. We will add them to an array then
// 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();
foreach ($models as $model) {
if (! is_null($value = $model->{$this->foreignKey})) {
$keys[] = $value;
}
}

// 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
13 changes: 13 additions & 0 deletions tests/Database/DatabaseEloquentBelongsToTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ public function testEagerConstraintsAreProperlyAdded()
$relation->addEagerConstraints($models);
}

public function testIdsInEagerConstraintsCanBeZero()
{
$relation = $this->getRelation();
$relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', ['foreign.value', 0]);
$models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStubWithZeroId];
$relation->addEagerConstraints($models);
}

public function testRelationIsProperlyInitialized()
{
$relation = $this->getRelation();
Expand Down Expand Up @@ -143,6 +151,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