diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php b/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php index 22f75a01eee9..94c42b4160c1 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php @@ -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 diff --git a/tests/Database/DatabaseEloquentBelongsToTest.php b/tests/Database/DatabaseEloquentBelongsToTest.php index d0b545a80524..1edf1abdbb3b 100755 --- a/tests/Database/DatabaseEloquentBelongsToTest.php +++ b/tests/Database/DatabaseEloquentBelongsToTest.php @@ -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(); @@ -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;