Skip to content
Closed
49 changes: 49 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -422,4 +422,53 @@ public function getLocalKeyName()
{
return $this->localKey;
}

/**
* Since eager loading returns empty relationship collections
* when foreignKey or localKey are missing, make sure, they are
* included in the $columns array.
*
* @param array $columns
* @return array
*/
protected function ensureKeyExistence($columns = ['*'])
{
if ($columns !== ['*'] && ! in_array($this->foreignKey, $columns)) {
$columns[] = $this->foreignKey;
}

if ($columns !== ['*'] && ! in_array($this->localKey, $columns)) {
$columns[] = $this->localKey;
}

return $columns;
}

/**
* Execute the query as a "select" statement.
*
* @param array $columns
* @return \Illuminate\Database\Eloquent\Collection
*/
public function get($columns = ['*'])
{
$columns = $this->ensureKeyExistence($columns);

return parent::get($columns);
}

/**
* Set the columns to be selected.
*
* @param array|mixed $columns
* @return $this
*/
public function select($columns = ['*'])
{
$columns = $this->ensureKeyExistence($columns);

parent::select($columns);

return $this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public function testLoadMissing()
$this->assertCount(2, DB::getQueryLog());
$this->assertTrue($posts[0]->comments[0]->relationLoaded('parent'));
$this->assertTrue($posts[0]->comments[1]->parent->relationLoaded('revisions'));
$this->assertArrayNotHasKey('id', $posts[0]->comments[1]->parent->revisions[0]->getAttributes());
$this->assertArrayHasKey('id', $posts[0]->comments[1]->parent->revisions[0]->getAttributes());
}

public function testLoadMissingWithClosure()
Expand Down