Skip to content

Commit

Permalink
Fix BelongsTo not accepting id == 0 in foreign relations (#17668)
Browse files Browse the repository at this point in the history
  • Loading branch information
antonioribeiro authored and taylorotwell committed Jan 30, 2017
1 parent 004162f commit d939078
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
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

0 comments on commit d939078

Please sign in to comment.