MorphTo.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use BadMethodCallException;
  4. use Illuminate\Database\Eloquent\Builder;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary;
  8. class MorphTo extends BelongsTo
  9. {
  10. use InteractsWithDictionary;
  11. /**
  12. * The type of the polymorphic relation.
  13. *
  14. * @var string
  15. */
  16. protected $morphType;
  17. /**
  18. * The models whose relations are being eager loaded.
  19. *
  20. * @var \Illuminate\Database\Eloquent\Collection
  21. */
  22. protected $models;
  23. /**
  24. * All of the models keyed by ID.
  25. *
  26. * @var array
  27. */
  28. protected $dictionary = [];
  29. /**
  30. * A buffer of dynamic calls to query macros.
  31. *
  32. * @var array
  33. */
  34. protected $macroBuffer = [];
  35. /**
  36. * A map of relations to load for each individual morph type.
  37. *
  38. * @var array
  39. */
  40. protected $morphableEagerLoads = [];
  41. /**
  42. * A map of relationship counts to load for each individual morph type.
  43. *
  44. * @var array
  45. */
  46. protected $morphableEagerLoadCounts = [];
  47. /**
  48. * A map of constraints to apply for each individual morph type.
  49. *
  50. * @var array
  51. */
  52. protected $morphableConstraints = [];
  53. /**
  54. * Create a new morph to relationship instance.
  55. *
  56. * @param \Illuminate\Database\Eloquent\Builder $query
  57. * @param \Illuminate\Database\Eloquent\Model $parent
  58. * @param string $foreignKey
  59. * @param string $ownerKey
  60. * @param string $type
  61. * @param string $relation
  62. * @return void
  63. */
  64. public function __construct(Builder $query, Model $parent, $foreignKey, $ownerKey, $type, $relation)
  65. {
  66. $this->morphType = $type;
  67. parent::__construct($query, $parent, $foreignKey, $ownerKey, $relation);
  68. }
  69. /**
  70. * Set the constraints for an eager load of the relation.
  71. *
  72. * @param array $models
  73. * @return void
  74. */
  75. public function addEagerConstraints(array $models)
  76. {
  77. $this->buildDictionary($this->models = Collection::make($models));
  78. }
  79. /**
  80. * Build a dictionary with the models.
  81. *
  82. * @param \Illuminate\Database\Eloquent\Collection $models
  83. * @return void
  84. */
  85. protected function buildDictionary(Collection $models)
  86. {
  87. foreach ($models as $model) {
  88. if ($model->{$this->morphType}) {
  89. $morphTypeKey = $this->getDictionaryKey($model->{$this->morphType});
  90. $foreignKeyKey = $this->getDictionaryKey($model->{$this->foreignKey});
  91. $this->dictionary[$morphTypeKey][$foreignKeyKey][] = $model;
  92. }
  93. }
  94. }
  95. /**
  96. * Get the results of the relationship.
  97. *
  98. * Called via eager load method of Eloquent query builder.
  99. *
  100. * @return mixed
  101. */
  102. public function getEager()
  103. {
  104. foreach (array_keys($this->dictionary) as $type) {
  105. $this->matchToMorphParents($type, $this->getResultsByType($type));
  106. }
  107. return $this->models;
  108. }
  109. /**
  110. * Get all of the relation results for a type.
  111. *
  112. * @param string $type
  113. * @return \Illuminate\Database\Eloquent\Collection
  114. */
  115. protected function getResultsByType($type)
  116. {
  117. $instance = $this->createModelByType($type);
  118. $ownerKey = $this->ownerKey ?? $instance->getKeyName();
  119. $query = $this->replayMacros($instance->newQuery())
  120. ->mergeConstraintsFrom($this->getQuery())
  121. ->with(array_merge(
  122. $this->getQuery()->getEagerLoads(),
  123. (array) ($this->morphableEagerLoads[get_class($instance)] ?? [])
  124. ))
  125. ->withCount(
  126. (array) ($this->morphableEagerLoadCounts[get_class($instance)] ?? [])
  127. );
  128. if ($callback = ($this->morphableConstraints[get_class($instance)] ?? null)) {
  129. $callback($query);
  130. }
  131. $whereIn = $this->whereInMethod($instance, $ownerKey);
  132. return $query->{$whereIn}(
  133. $instance->getTable().'.'.$ownerKey, $this->gatherKeysByType($type, $instance->getKeyType())
  134. )->get();
  135. }
  136. /**
  137. * Gather all of the foreign keys for a given type.
  138. *
  139. * @param string $type
  140. * @param string $keyType
  141. * @return array
  142. */
  143. protected function gatherKeysByType($type, $keyType)
  144. {
  145. return $keyType !== 'string'
  146. ? array_keys($this->dictionary[$type])
  147. : array_map(function ($modelId) {
  148. return (string) $modelId;
  149. }, array_filter(array_keys($this->dictionary[$type])));
  150. }
  151. /**
  152. * Create a new model instance by type.
  153. *
  154. * @param string $type
  155. * @return \Illuminate\Database\Eloquent\Model
  156. */
  157. public function createModelByType($type)
  158. {
  159. $class = Model::getActualClassNameForMorph($type);
  160. return tap(new $class, function ($instance) {
  161. if (! $instance->getConnectionName()) {
  162. $instance->setConnection($this->getConnection()->getName());
  163. }
  164. });
  165. }
  166. /**
  167. * Match the eagerly loaded results to their parents.
  168. *
  169. * @param array $models
  170. * @param \Illuminate\Database\Eloquent\Collection $results
  171. * @param string $relation
  172. * @return array
  173. */
  174. public function match(array $models, Collection $results, $relation)
  175. {
  176. return $models;
  177. }
  178. /**
  179. * Match the results for a given type to their parents.
  180. *
  181. * @param string $type
  182. * @param \Illuminate\Database\Eloquent\Collection $results
  183. * @return void
  184. */
  185. protected function matchToMorphParents($type, Collection $results)
  186. {
  187. foreach ($results as $result) {
  188. $ownerKey = ! is_null($this->ownerKey) ? $this->getDictionaryKey($result->{$this->ownerKey}) : $result->getKey();
  189. if (isset($this->dictionary[$type][$ownerKey])) {
  190. foreach ($this->dictionary[$type][$ownerKey] as $model) {
  191. $model->setRelation($this->relationName, $result);
  192. }
  193. }
  194. }
  195. }
  196. /**
  197. * Associate the model instance to the given parent.
  198. *
  199. * @param \Illuminate\Database\Eloquent\Model|null $model
  200. * @return \Illuminate\Database\Eloquent\Model
  201. */
  202. public function associate($model)
  203. {
  204. if ($model instanceof Model) {
  205. $foreignKey = $this->ownerKey && $model->{$this->ownerKey}
  206. ? $this->ownerKey
  207. : $model->getKeyName();
  208. }
  209. $this->parent->setAttribute(
  210. $this->foreignKey, $model instanceof Model ? $model->{$foreignKey} : null
  211. );
  212. $this->parent->setAttribute(
  213. $this->morphType, $model instanceof Model ? $model->getMorphClass() : null
  214. );
  215. return $this->parent->setRelation($this->relationName, $model);
  216. }
  217. /**
  218. * Dissociate previously associated model from the given parent.
  219. *
  220. * @return \Illuminate\Database\Eloquent\Model
  221. */
  222. public function dissociate()
  223. {
  224. $this->parent->setAttribute($this->foreignKey, null);
  225. $this->parent->setAttribute($this->morphType, null);
  226. return $this->parent->setRelation($this->relationName, null);
  227. }
  228. /**
  229. * Touch all of the related models for the relationship.
  230. *
  231. * @return void
  232. */
  233. public function touch()
  234. {
  235. if (! is_null($this->child->{$this->foreignKey})) {
  236. parent::touch();
  237. }
  238. }
  239. /**
  240. * Make a new related instance for the given model.
  241. *
  242. * @param \Illuminate\Database\Eloquent\Model $parent
  243. * @return \Illuminate\Database\Eloquent\Model
  244. */
  245. protected function newRelatedInstanceFor(Model $parent)
  246. {
  247. return $parent->{$this->getRelationName()}()->getRelated()->newInstance();
  248. }
  249. /**
  250. * Get the foreign key "type" name.
  251. *
  252. * @return string
  253. */
  254. public function getMorphType()
  255. {
  256. return $this->morphType;
  257. }
  258. /**
  259. * Get the dictionary used by the relationship.
  260. *
  261. * @return array
  262. */
  263. public function getDictionary()
  264. {
  265. return $this->dictionary;
  266. }
  267. /**
  268. * Specify which relations to load for a given morph type.
  269. *
  270. * @param array $with
  271. * @return \Illuminate\Database\Eloquent\Relations\MorphTo
  272. */
  273. public function morphWith(array $with)
  274. {
  275. $this->morphableEagerLoads = array_merge(
  276. $this->morphableEagerLoads, $with
  277. );
  278. return $this;
  279. }
  280. /**
  281. * Specify which relationship counts to load for a given morph type.
  282. *
  283. * @param array $withCount
  284. * @return \Illuminate\Database\Eloquent\Relations\MorphTo
  285. */
  286. public function morphWithCount(array $withCount)
  287. {
  288. $this->morphableEagerLoadCounts = array_merge(
  289. $this->morphableEagerLoadCounts, $withCount
  290. );
  291. return $this;
  292. }
  293. /**
  294. * Specify constraints on the query for a given morph type.
  295. *
  296. * @param array $callbacks
  297. * @return \Illuminate\Database\Eloquent\Relations\MorphTo
  298. */
  299. public function constrain(array $callbacks)
  300. {
  301. $this->morphableConstraints = array_merge(
  302. $this->morphableConstraints, $callbacks
  303. );
  304. return $this;
  305. }
  306. /**
  307. * Indicate that soft deleted models should be included in the results.
  308. *
  309. * @return $this
  310. */
  311. public function withTrashed()
  312. {
  313. $callback = fn ($query) => $query->hasMacro('withTrashed') ? $query->withTrashed() : $query;
  314. $this->macroBuffer[] = [
  315. 'method' => 'when',
  316. 'parameters' => [true, $callback],
  317. ];
  318. return $this->when(true, $callback);
  319. }
  320. /**
  321. * Indicate that soft deleted models should not be included in the results.
  322. *
  323. * @return $this
  324. */
  325. public function withoutTrashed()
  326. {
  327. $callback = fn ($query) => $query->hasMacro('withoutTrashed') ? $query->withoutTrashed() : $query;
  328. $this->macroBuffer[] = [
  329. 'method' => 'when',
  330. 'parameters' => [true, $callback],
  331. ];
  332. return $this->when(true, $callback);
  333. }
  334. /**
  335. * Indicate that only soft deleted models should be included in the results.
  336. *
  337. * @return $this
  338. */
  339. public function onlyTrashed()
  340. {
  341. $callback = fn ($query) => $query->hasMacro('onlyTrashed') ? $query->onlyTrashed() : $query;
  342. $this->macroBuffer[] = [
  343. 'method' => 'when',
  344. 'parameters' => [true, $callback],
  345. ];
  346. return $this->when(true, $callback);
  347. }
  348. /**
  349. * Replay stored macro calls on the actual related instance.
  350. *
  351. * @param \Illuminate\Database\Eloquent\Builder $query
  352. * @return \Illuminate\Database\Eloquent\Builder
  353. */
  354. protected function replayMacros(Builder $query)
  355. {
  356. foreach ($this->macroBuffer as $macro) {
  357. $query->{$macro['method']}(...$macro['parameters']);
  358. }
  359. return $query;
  360. }
  361. /**
  362. * Handle dynamic method calls to the relationship.
  363. *
  364. * @param string $method
  365. * @param array $parameters
  366. * @return mixed
  367. */
  368. public function __call($method, $parameters)
  369. {
  370. try {
  371. $result = parent::__call($method, $parameters);
  372. if (in_array($method, ['select', 'selectRaw', 'selectSub', 'addSelect', 'withoutGlobalScopes'])) {
  373. $this->macroBuffer[] = compact('method', 'parameters');
  374. }
  375. return $result;
  376. }
  377. // If we tried to call a method that does not exist on the parent Builder instance,
  378. // we'll assume that we want to call a query macro (e.g. withTrashed) that only
  379. // exists on related models. We will just store the call and replay it later.
  380. catch (BadMethodCallException) {
  381. $this->macroBuffer[] = compact('method', 'parameters');
  382. return $this;
  383. }
  384. }
  385. }