HasOneThrough.php 2.1 KB

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