MorphTo.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 ? $this->query->first() : 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. $query = $this->replayMacros($instance->newQuery())
  109. ->mergeConstraintsFrom($this->getQuery())
  110. ->with($this->getQuery()->getEagerLoads());
  111. return $query->whereIn(
  112. $instance->getTable().'.'.$instance->getKeyName(), $this->gatherKeysByType($type)
  113. )->get();
  114. }
  115. /**
  116. * Gather all of the foreign keys for a given type.
  117. *
  118. * @param string $type
  119. * @return array
  120. */
  121. protected function gatherKeysByType($type)
  122. {
  123. return collect($this->dictionary[$type])->map(function ($models) {
  124. return head($models)->{$this->foreignKey};
  125. })->values()->unique()->all();
  126. }
  127. /**
  128. * Create a new model instance by type.
  129. *
  130. * @param string $type
  131. * @return \Illuminate\Database\Eloquent\Model
  132. */
  133. public function createModelByType($type)
  134. {
  135. $class = Model::getActualClassNameForMorph($type);
  136. return new $class;
  137. }
  138. /**
  139. * Match the eagerly loaded results to their parents.
  140. *
  141. * @param array $models
  142. * @param \Illuminate\Database\Eloquent\Collection $results
  143. * @param string $relation
  144. * @return array
  145. */
  146. public function match(array $models, Collection $results, $relation)
  147. {
  148. return $models;
  149. }
  150. /**
  151. * Match the results for a given type to their parents.
  152. *
  153. * @param string $type
  154. * @param \Illuminate\Database\Eloquent\Collection $results
  155. * @return void
  156. */
  157. protected function matchToMorphParents($type, Collection $results)
  158. {
  159. foreach ($results as $result) {
  160. if (isset($this->dictionary[$type][$result->getKey()])) {
  161. foreach ($this->dictionary[$type][$result->getKey()] as $model) {
  162. $model->setRelation($this->relation, $result);
  163. }
  164. }
  165. }
  166. }
  167. /**
  168. * Associate the model instance to the given parent.
  169. *
  170. * @param \Illuminate\Database\Eloquent\Model $model
  171. * @return \Illuminate\Database\Eloquent\Model
  172. */
  173. public function associate($model)
  174. {
  175. $this->parent->setAttribute(
  176. $this->foreignKey, $model instanceof Model ? $model->getKey() : null
  177. );
  178. $this->parent->setAttribute(
  179. $this->morphType, $model instanceof Model ? $model->getMorphClass() : null
  180. );
  181. return $this->parent->setRelation($this->relation, $model);
  182. }
  183. /**
  184. * Dissociate previously associated model from the given parent.
  185. *
  186. * @return \Illuminate\Database\Eloquent\Model
  187. */
  188. public function dissociate()
  189. {
  190. $this->parent->setAttribute($this->foreignKey, null);
  191. $this->parent->setAttribute($this->morphType, null);
  192. return $this->parent->setRelation($this->relation, null);
  193. }
  194. /**
  195. * Get the foreign key "type" name.
  196. *
  197. * @return string
  198. */
  199. public function getMorphType()
  200. {
  201. return $this->morphType;
  202. }
  203. /**
  204. * Get the dictionary used by the relationship.
  205. *
  206. * @return array
  207. */
  208. public function getDictionary()
  209. {
  210. return $this->dictionary;
  211. }
  212. /**
  213. * Replay stored macro calls on the actual related instance.
  214. *
  215. * @param \Illuminate\Database\Eloquent\Builder $query
  216. * @return \Illuminate\Database\Eloquent\Builder
  217. */
  218. protected function replayMacros(Builder $query)
  219. {
  220. foreach ($this->macroBuffer as $macro) {
  221. $query->{$macro['method']}(...$macro['parameters']);
  222. }
  223. return $query;
  224. }
  225. /**
  226. * Handle dynamic method calls to the relationship.
  227. *
  228. * @param string $method
  229. * @param array $parameters
  230. * @return mixed
  231. */
  232. public function __call($method, $parameters)
  233. {
  234. try {
  235. return parent::__call($method, $parameters);
  236. }
  237. // If we tried to call a method that does not exist on the parent Builder instance,
  238. // we'll assume that we want to call a query macro (e.g. withTrashed) that only
  239. // exists on related models. We will just store the call and replay it later.
  240. catch (BadMethodCallException $e) {
  241. $this->macroBuffer[] = compact('method', 'parameters');
  242. return $this;
  243. }
  244. }
  245. }