MorphTo.php 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use BadMethodCallException;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Builder;
  6. use Illuminate\Database\Eloquent\Collection;
  7. /**
  8. * @mixin \Illuminate\Database\Eloquent\Builder
  9. */
  10. class MorphTo extends BelongsTo
  11. {
  12. /**
  13. * The type of the polymorphic relation.
  14. *
  15. * @var string
  16. */
  17. protected $morphType;
  18. /**
  19. * The models whose relations are being eager loaded.
  20. *
  21. * @var \Illuminate\Database\Eloquent\Collection
  22. */
  23. protected $models;
  24. /**
  25. * All of the models keyed by ID.
  26. *
  27. * @var array
  28. */
  29. protected $dictionary = [];
  30. /**
  31. * A buffer of dynamic calls to query macros.
  32. *
  33. * @var array
  34. */
  35. protected $macroBuffer = [];
  36. /**
  37. * Create a new morph to relationship instance.
  38. *
  39. * @param \Illuminate\Database\Eloquent\Builder $query
  40. * @param \Illuminate\Database\Eloquent\Model $parent
  41. * @param string $foreignKey
  42. * @param string $ownerKey
  43. * @param string $type
  44. * @param string $relation
  45. * @return void
  46. */
  47. public function __construct(Builder $query, Model $parent, $foreignKey, $ownerKey, $type, $relation)
  48. {
  49. $this->morphType = $type;
  50. parent::__construct($query, $parent, $foreignKey, $ownerKey, $relation);
  51. }
  52. /**
  53. * Set the constraints for an eager load of the relation.
  54. *
  55. * @param array $models
  56. * @return void
  57. */
  58. public function addEagerConstraints(array $models)
  59. {
  60. $this->buildDictionary($this->models = Collection::make($models));
  61. }
  62. /**
  63. * Build a dictionary with the models.
  64. *
  65. * @param \Illuminate\Database\Eloquent\Collection $models
  66. * @return void
  67. */
  68. protected function buildDictionary(Collection $models)
  69. {
  70. foreach ($models as $model) {
  71. if ($model->{$this->morphType}) {
  72. $this->dictionary[$model->{$this->morphType}][$model->{$this->foreignKey}][] = $model;
  73. }
  74. }
  75. }
  76. /**
  77. * Get the results of the relationship.
  78. *
  79. * @return mixed
  80. */
  81. public function getResults()
  82. {
  83. return $this->ownerKey ? parent::getResults() : null;
  84. }
  85. /**
  86. * Get the results of the relationship.
  87. *
  88. * Called via eager load method of Eloquent query builder.
  89. *
  90. * @return mixed
  91. */
  92. public function getEager()
  93. {
  94. foreach (array_keys($this->dictionary) as $type) {
  95. $this->matchToMorphParents($type, $this->getResultsByType($type));
  96. }
  97. return $this->models;
  98. }
  99. /**
  100. * Get all of the relation results for a type.
  101. *
  102. * @param string $type
  103. * @return \Illuminate\Database\Eloquent\Collection
  104. */
  105. protected function getResultsByType($type)
  106. {
  107. $instance = $this->createModelByType($type);
  108. $ownerKey = $this->ownerKey ?? $instance->getKeyName();
  109. $query = $this->replayMacros($instance->newQuery())
  110. ->mergeConstraintsFrom($this->getQuery())
  111. ->with($this->getQuery()->getEagerLoads());
  112. return $query->whereIn(
  113. $instance->getTable().'.'.$ownerKey, $this->gatherKeysByType($type)
  114. )->get();
  115. }
  116. /**
  117. * Gather all of the foreign keys for a given type.
  118. *
  119. * @param string $type
  120. * @return array
  121. */
  122. protected function gatherKeysByType($type)
  123. {
  124. return collect($this->dictionary[$type])->map(function ($models) {
  125. return head($models)->{$this->foreignKey};
  126. })->values()->unique()->all();
  127. }
  128. /**
  129. * Create a new model instance by type.
  130. *
  131. * @param string $type
  132. * @return \Illuminate\Database\Eloquent\Model
  133. */
  134. public function createModelByType($type)
  135. {
  136. $class = Model::getActualClassNameForMorph($type);
  137. return new $class;
  138. }
  139. /**
  140. * Match the eagerly loaded results to their parents.
  141. *
  142. * @param array $models
  143. * @param \Illuminate\Database\Eloquent\Collection $results
  144. * @param string $relation
  145. * @return array
  146. */
  147. public function match(array $models, Collection $results, $relation)
  148. {
  149. return $models;
  150. }
  151. /**
  152. * Match the results for a given type to their parents.
  153. *
  154. * @param string $type
  155. * @param \Illuminate\Database\Eloquent\Collection $results
  156. * @return void
  157. */
  158. protected function matchToMorphParents($type, Collection $results)
  159. {
  160. foreach ($results as $result) {
  161. $ownerKey = ! is_null($this->ownerKey) ? $result->{$this->ownerKey} : $result->getKey();
  162. if (isset($this->dictionary[$type][$ownerKey])) {
  163. foreach ($this->dictionary[$type][$ownerKey] as $model) {
  164. $model->setRelation($this->relation, $result);
  165. }
  166. }
  167. }
  168. }
  169. /**
  170. * Associate the model instance to the given parent.
  171. *
  172. * @param \Illuminate\Database\Eloquent\Model $model
  173. * @return \Illuminate\Database\Eloquent\Model
  174. */
  175. public function associate($model)
  176. {
  177. $this->parent->setAttribute(
  178. $this->foreignKey, $model instanceof Model ? $model->getKey() : null
  179. );
  180. $this->parent->setAttribute(
  181. $this->morphType, $model instanceof Model ? $model->getMorphClass() : null
  182. );
  183. return $this->parent->setRelation($this->relation, $model);
  184. }
  185. /**
  186. * Dissociate previously associated model from the given parent.
  187. *
  188. * @return \Illuminate\Database\Eloquent\Model
  189. */
  190. public function dissociate()
  191. {
  192. $this->parent->setAttribute($this->foreignKey, null);
  193. $this->parent->setAttribute($this->morphType, null);
  194. return $this->parent->setRelation($this->relation, null);
  195. }
  196. /**
  197. * Get the foreign key "type" name.
  198. *
  199. * @return string
  200. */
  201. public function getMorphType()
  202. {
  203. return $this->morphType;
  204. }
  205. /**
  206. * Get the dictionary used by the relationship.
  207. *
  208. * @return array
  209. */
  210. public function getDictionary()
  211. {
  212. return $this->dictionary;
  213. }
  214. /**
  215. * Replay stored macro calls on the actual related instance.
  216. *
  217. * @param \Illuminate\Database\Eloquent\Builder $query
  218. * @return \Illuminate\Database\Eloquent\Builder
  219. */
  220. protected function replayMacros(Builder $query)
  221. {
  222. foreach ($this->macroBuffer as $macro) {
  223. $query->{$macro['method']}(...$macro['parameters']);
  224. }
  225. return $query;
  226. }
  227. /**
  228. * Handle dynamic method calls to the relationship.
  229. *
  230. * @param string $method
  231. * @param array $parameters
  232. * @return mixed
  233. */
  234. public function __call($method, $parameters)
  235. {
  236. try {
  237. return parent::__call($method, $parameters);
  238. }
  239. // If we tried to call a method that does not exist on the parent Builder instance,
  240. // we'll assume that we want to call a query macro (e.g. withTrashed) that only
  241. // exists on related models. We will just store the call and replay it later.
  242. catch (BadMethodCallException $e) {
  243. $this->macroBuffer[] = compact('method', 'parameters');
  244. return $this;
  245. }
  246. }
  247. }