Skip to content

Commit

Permalink
Make has one with default work with eager loading as well.
Browse files Browse the repository at this point in the history
  • Loading branch information
sileence committed Nov 10, 2016
1 parent 5f1542e commit 5f1d2e0
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/Illuminate/Database/Eloquent/Relations/HasOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Database\Eloquent\Relations;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class HasOne extends HasOneOrMany
Expand Down Expand Up @@ -32,16 +33,7 @@ public function withDefault()
*/
public function getResults()
{
if ($result = $this->query->first()) {
return $result;
}

if ($this->withDefault) {
return $this->related->newInstance()
->setAttribute(
$this->getPlainForeignKey(), $this->getParentKey()
);
}
return $this->query->first() ?: $this->getDefaultFor($this->parent);
}

/**
Expand All @@ -54,7 +46,7 @@ public function getResults()
public function initRelation(array $models, $relation)
{
foreach ($models as $model) {
$model->setRelation($relation, null);
$model->setRelation($relation, $this->getDefaultFor($model));
}

return $models;
Expand All @@ -63,7 +55,7 @@ public function initRelation(array $models, $relation)
/**
* Match the eagerly loaded results to their parents.
*
* @param array $models
* @param array $models
* @param \Illuminate\Database\Eloquent\Collection $results
* @param string $relation
* @return array
Expand All @@ -72,4 +64,19 @@ public function match(array $models, Collection $results, $relation)
{
return $this->matchOne($models, $results, $relation);
}

/**
* Get the default value for this relation.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Database\Eloquent\Model|null
*/
protected function getDefaultFor(Model $model)
{
if ($this->withDefault) {
return $this->related->newInstance()->setAttribute(
$this->getPlainForeignKey(), $model->getAttribute($this->localKey)
);
}
}
}

0 comments on commit 5f1d2e0

Please sign in to comment.