MorphMany.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use Illuminate\Database\Eloquent\Collection;
  4. use Illuminate\Database\Eloquent\Model;
  5. class MorphMany extends MorphOneOrMany
  6. {
  7. /**
  8. * Convert the relationship to a "morph one" relationship.
  9. *
  10. * @return \Illuminate\Database\Eloquent\Relations\MorphOne
  11. */
  12. public function one()
  13. {
  14. return MorphOne::noConstraints(fn () => new MorphOne(
  15. $this->getQuery(),
  16. $this->getParent(),
  17. $this->morphType,
  18. $this->foreignKey,
  19. $this->localKey
  20. ));
  21. }
  22. /**
  23. * Get the results of the relationship.
  24. *
  25. * @return mixed
  26. */
  27. public function getResults()
  28. {
  29. return ! is_null($this->getParentKey())
  30. ? $this->query->get()
  31. : $this->related->newCollection();
  32. }
  33. /**
  34. * Initialize the relation on a set of models.
  35. *
  36. * @param array $models
  37. * @param string $relation
  38. * @return array
  39. */
  40. public function initRelation(array $models, $relation)
  41. {
  42. foreach ($models as $model) {
  43. $model->setRelation($relation, $this->related->newCollection());
  44. }
  45. return $models;
  46. }
  47. /**
  48. * Match the eagerly loaded results to their parents.
  49. *
  50. * @param array $models
  51. * @param \Illuminate\Database\Eloquent\Collection $results
  52. * @param string $relation
  53. * @return array
  54. */
  55. public function match(array $models, Collection $results, $relation)
  56. {
  57. return $this->matchMany($models, $results, $relation);
  58. }
  59. /**
  60. * Create a new instance of the related model. Allow mass-assignment.
  61. *
  62. * @param array $attributes
  63. * @return \Illuminate\Database\Eloquent\Model
  64. */
  65. public function forceCreate(array $attributes = [])
  66. {
  67. $attributes[$this->getMorphType()] = $this->morphClass;
  68. return parent::forceCreate($attributes);
  69. }
  70. /**
  71. * Create a new instance of the related model with mass assignment without raising model events.
  72. *
  73. * @param array $attributes
  74. * @return \Illuminate\Database\Eloquent\Model
  75. */
  76. public function forceCreateQuietly(array $attributes = [])
  77. {
  78. return Model::withoutEvents(fn () => $this->forceCreate($attributes));
  79. }
  80. }