HasMany.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use Illuminate\Database\Eloquent\Collection;
  4. class HasMany extends HasOneOrMany
  5. {
  6. /**
  7. * Convert the relationship to a "has one" relationship.
  8. *
  9. * @return \Illuminate\Database\Eloquent\Relations\HasOne
  10. */
  11. public function one()
  12. {
  13. return HasOne::noConstraints(fn () => new HasOne(
  14. $this->getQuery(),
  15. $this->parent,
  16. $this->foreignKey,
  17. $this->localKey
  18. ));
  19. }
  20. /**
  21. * Get the results of the relationship.
  22. *
  23. * @return mixed
  24. */
  25. public function getResults()
  26. {
  27. return ! is_null($this->getParentKey())
  28. ? $this->query->get()
  29. : $this->related->newCollection();
  30. }
  31. /**
  32. * Initialize the relation on a set of models.
  33. *
  34. * @param array $models
  35. * @param string $relation
  36. * @return array
  37. */
  38. public function initRelation(array $models, $relation)
  39. {
  40. foreach ($models as $model) {
  41. $model->setRelation($relation, $this->related->newCollection());
  42. }
  43. return $models;
  44. }
  45. /**
  46. * Match the eagerly loaded results to their parents.
  47. *
  48. * @param array $models
  49. * @param \Illuminate\Database\Eloquent\Collection $results
  50. * @param string $relation
  51. * @return array
  52. */
  53. public function match(array $models, Collection $results, $relation)
  54. {
  55. return $this->matchMany($models, $results, $relation);
  56. }
  57. }