Skip to content

Commit d35df12

Browse files
Fix BelongsTo not accepting id == 0 in foreign relations
1 parent 25c9d06 commit d35df12

File tree

2 files changed

+9
-9
lines changed

2 files changed

+9
-9
lines changed

src/Illuminate/Database/Eloquent/Relations/BelongsTo.php

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -116,16 +116,16 @@ public function addEagerConstraints(array $models)
116116
*/
117117
protected function getEagerModelKeys(array $models)
118118
{
119+
$keys = [];
120+
119121
// First we need to gather all of the keys from the parent models so we know what
120122
// to query for via the eager loading query. We will add them to an array then
121123
// execute a "where in" statement to gather up all of those related records.
122-
$keys = collect($models)->map(function ($model) {
123-
return $model->{$this->foreignKey};
124-
})->filter(function ($value) {
125-
return (! is_null($value)) &&
126-
(! is_bool($value) || $value !== false) &&
127-
(! is_string($value) || $value !== '');
128-
})->all();
124+
foreach ($models as $model) {
125+
if (! is_null($value = $model->{$this->foreignKey})) {
126+
$keys[] = $value;
127+
}
128+
}
129129

130130
// If there are no keys that were not null we will just return an array with either
131131
// null or 0 in (depending on if incrementing keys are in use) so the query wont

tests/Database/DatabaseEloquentBelongsToTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public function testIdsInEagerConstraintsCanBeZero()
3737
{
3838
$relation = $this->getRelation();
3939
$relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', ['foreign.value', 0]);
40-
$models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStubWithIdZero];
40+
$models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStubWithZeroId];
4141
$relation->addEagerConstraints($models);
4242
}
4343

@@ -151,7 +151,7 @@ class AnotherEloquentBelongsToModelStub extends \Illuminate\Database\Eloquent\Mo
151151
public $foreign_key = 'foreign.value.two';
152152
}
153153

154-
class EloquentBelongsToModelStubWithIdZero extends \Illuminate\Database\Eloquent\Model
154+
class EloquentBelongsToModelStubWithZeroId extends \Illuminate\Database\Eloquent\Model
155155
{
156156
public $foreign_key = 0;
157157
}

0 commit comments

Comments
 (0)