HasOneThrough.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use Illuminate\Database\Eloquent\Collection;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary;
  6. use Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels;
  7. class HasOneThrough extends HasManyThrough
  8. {
  9. use InteractsWithDictionary, SupportsDefaultModels;
  10. /**
  11. * Get the results of the relationship.
  12. *
  13. * @return mixed
  14. */
  15. public function getResults()
  16. {
  17. return $this->first() ?: $this->getDefaultFor($this->farParent);
  18. }
  19. /**
  20. * Initialize the relation on a set of models.
  21. *
  22. * @param array $models
  23. * @param string $relation
  24. * @return array
  25. */
  26. public function initRelation(array $models, $relation)
  27. {
  28. foreach ($models as $model) {
  29. $model->setRelation($relation, $this->getDefaultFor($model));
  30. }
  31. return $models;
  32. }
  33. /**
  34. * Match the eagerly loaded results to their parents.
  35. *
  36. * @param array $models
  37. * @param \Illuminate\Database\Eloquent\Collection $results
  38. * @param string $relation
  39. * @return array
  40. */
  41. public function match(array $models, Collection $results, $relation)
  42. {
  43. $dictionary = $this->buildDictionary($results);
  44. // Once we have the dictionary we can simply spin through the parent models to
  45. // link them up with their children using the keyed dictionary to make the
  46. // matching very convenient and easy work. Then we'll just return them.
  47. foreach ($models as $model) {
  48. if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) {
  49. $value = $dictionary[$key];
  50. $model->setRelation(
  51. $relation, reset($value)
  52. );
  53. }
  54. }
  55. return $models;
  56. }
  57. /**
  58. * Make a new related instance for the given model.
  59. *
  60. * @param \Illuminate\Database\Eloquent\Model $parent
  61. * @return \Illuminate\Database\Eloquent\Model
  62. */
  63. public function newRelatedInstanceFor(Model $parent)
  64. {
  65. return $this->related->newInstance();
  66. }
  67. }