HasOne.php 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Collection;
  5. use Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels;
  6. class HasOne extends HasOneOrMany
  7. {
  8. use SupportsDefaultModels;
  9. /**
  10. * Get the results of the relationship.
  11. *
  12. * @return mixed
  13. */
  14. public function getResults()
  15. {
  16. return $this->query->first() ?: $this->getDefaultFor($this->parent);
  17. }
  18. /**
  19. * Initialize the relation on a set of models.
  20. *
  21. * @param array $models
  22. * @param string $relation
  23. * @return array
  24. */
  25. public function initRelation(array $models, $relation)
  26. {
  27. foreach ($models as $model) {
  28. $model->setRelation($relation, $this->getDefaultFor($model));
  29. }
  30. return $models;
  31. }
  32. /**
  33. * Match the eagerly loaded results to their parents.
  34. *
  35. * @param array $models
  36. * @param \Illuminate\Database\Eloquent\Collection $results
  37. * @param string $relation
  38. * @return array
  39. */
  40. public function match(array $models, Collection $results, $relation)
  41. {
  42. return $this->matchOne($models, $results, $relation);
  43. }
  44. /**
  45. * Make a new related instance for the given model.
  46. *
  47. * @param \Illuminate\Database\Eloquent\Model $parent
  48. * @return \Illuminate\Database\Eloquent\Model
  49. */
  50. public function newRelatedInstanceFor(Model $parent)
  51. {
  52. return $this->related->newInstance()->setAttribute(
  53. $this->getForeignKeyName(), $parent->{$this->localKey}
  54. );
  55. }
  56. }