Relation.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use Closure;
  4. use Illuminate\Contracts\Database\Eloquent\Builder as BuilderContract;
  5. use Illuminate\Database\Eloquent\Builder;
  6. use Illuminate\Database\Eloquent\Collection;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Database\Eloquent\ModelNotFoundException;
  9. use Illuminate\Database\MultipleRecordsFoundException;
  10. use Illuminate\Database\Query\Expression;
  11. use Illuminate\Support\Traits\ForwardsCalls;
  12. use Illuminate\Support\Traits\Macroable;
  13. abstract class Relation implements BuilderContract
  14. {
  15. use ForwardsCalls, Macroable {
  16. Macroable::__call as macroCall;
  17. }
  18. /**
  19. * The Eloquent query builder instance.
  20. *
  21. * @var \Illuminate\Database\Eloquent\Builder
  22. */
  23. protected $query;
  24. /**
  25. * The parent model instance.
  26. *
  27. * @var \Illuminate\Database\Eloquent\Model
  28. */
  29. protected $parent;
  30. /**
  31. * The related model instance.
  32. *
  33. * @var \Illuminate\Database\Eloquent\Model
  34. */
  35. protected $related;
  36. /**
  37. * Indicates whether the eagerly loaded relation should implicitly return an empty collection.
  38. *
  39. * @var bool
  40. */
  41. protected $eagerKeysWereEmpty = false;
  42. /**
  43. * Indicates if the relation is adding constraints.
  44. *
  45. * @var bool
  46. */
  47. protected static $constraints = true;
  48. /**
  49. * An array to map class names to their morph names in the database.
  50. *
  51. * @var array
  52. */
  53. public static $morphMap = [];
  54. /**
  55. * Prevents morph relationships without a morph map.
  56. *
  57. * @var bool
  58. */
  59. protected static $requireMorphMap = false;
  60. /**
  61. * The count of self joins.
  62. *
  63. * @var int
  64. */
  65. protected static $selfJoinCount = 0;
  66. /**
  67. * Create a new relation instance.
  68. *
  69. * @param \Illuminate\Database\Eloquent\Builder $query
  70. * @param \Illuminate\Database\Eloquent\Model $parent
  71. * @return void
  72. */
  73. public function __construct(Builder $query, Model $parent)
  74. {
  75. $this->query = $query;
  76. $this->parent = $parent;
  77. $this->related = $query->getModel();
  78. $this->addConstraints();
  79. }
  80. /**
  81. * Run a callback with constraints disabled on the relation.
  82. *
  83. * @param \Closure $callback
  84. * @return mixed
  85. */
  86. public static function noConstraints(Closure $callback)
  87. {
  88. $previous = static::$constraints;
  89. static::$constraints = false;
  90. // When resetting the relation where clause, we want to shift the first element
  91. // off of the bindings, leaving only the constraints that the developers put
  92. // as "extra" on the relationships, and not original relation constraints.
  93. try {
  94. return $callback();
  95. } finally {
  96. static::$constraints = $previous;
  97. }
  98. }
  99. /**
  100. * Set the base constraints on the relation query.
  101. *
  102. * @return void
  103. */
  104. abstract public function addConstraints();
  105. /**
  106. * Set the constraints for an eager load of the relation.
  107. *
  108. * @param array $models
  109. * @return void
  110. */
  111. abstract public function addEagerConstraints(array $models);
  112. /**
  113. * Initialize the relation on a set of models.
  114. *
  115. * @param array $models
  116. * @param string $relation
  117. * @return array
  118. */
  119. abstract public function initRelation(array $models, $relation);
  120. /**
  121. * Match the eagerly loaded results to their parents.
  122. *
  123. * @param array $models
  124. * @param \Illuminate\Database\Eloquent\Collection $results
  125. * @param string $relation
  126. * @return array
  127. */
  128. abstract public function match(array $models, Collection $results, $relation);
  129. /**
  130. * Get the results of the relationship.
  131. *
  132. * @return mixed
  133. */
  134. abstract public function getResults();
  135. /**
  136. * Get the relationship for eager loading.
  137. *
  138. * @return \Illuminate\Database\Eloquent\Collection
  139. */
  140. public function getEager()
  141. {
  142. return $this->eagerKeysWereEmpty
  143. ? $this->query->getModel()->newCollection()
  144. : $this->get();
  145. }
  146. /**
  147. * Execute the query and get the first result if it's the sole matching record.
  148. *
  149. * @param array|string $columns
  150. * @return \Illuminate\Database\Eloquent\Model
  151. *
  152. * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model>
  153. * @throws \Illuminate\Database\MultipleRecordsFoundException
  154. */
  155. public function sole($columns = ['*'])
  156. {
  157. $result = $this->take(2)->get($columns);
  158. $count = $result->count();
  159. if ($count === 0) {
  160. throw (new ModelNotFoundException)->setModel(get_class($this->related));
  161. }
  162. if ($count > 1) {
  163. throw new MultipleRecordsFoundException($count);
  164. }
  165. return $result->first();
  166. }
  167. /**
  168. * Execute the query as a "select" statement.
  169. *
  170. * @param array $columns
  171. * @return \Illuminate\Database\Eloquent\Collection
  172. */
  173. public function get($columns = ['*'])
  174. {
  175. return $this->query->get($columns);
  176. }
  177. /**
  178. * Touch all of the related models for the relationship.
  179. *
  180. * @return void
  181. */
  182. public function touch()
  183. {
  184. $model = $this->getRelated();
  185. if (! $model::isIgnoringTouch()) {
  186. $this->rawUpdate([
  187. $model->getUpdatedAtColumn() => $model->freshTimestampString(),
  188. ]);
  189. }
  190. }
  191. /**
  192. * Run a raw update against the base query.
  193. *
  194. * @param array $attributes
  195. * @return int
  196. */
  197. public function rawUpdate(array $attributes = [])
  198. {
  199. return $this->query->withoutGlobalScopes()->update($attributes);
  200. }
  201. /**
  202. * Add the constraints for a relationship count query.
  203. *
  204. * @param \Illuminate\Database\Eloquent\Builder $query
  205. * @param \Illuminate\Database\Eloquent\Builder $parentQuery
  206. * @return \Illuminate\Database\Eloquent\Builder
  207. */
  208. public function getRelationExistenceCountQuery(Builder $query, Builder $parentQuery)
  209. {
  210. return $this->getRelationExistenceQuery(
  211. $query, $parentQuery, new Expression('count(*)')
  212. )->setBindings([], 'select');
  213. }
  214. /**
  215. * Add the constraints for an internal relationship existence query.
  216. *
  217. * Essentially, these queries compare on column names like whereColumn.
  218. *
  219. * @param \Illuminate\Database\Eloquent\Builder $query
  220. * @param \Illuminate\Database\Eloquent\Builder $parentQuery
  221. * @param array|mixed $columns
  222. * @return \Illuminate\Database\Eloquent\Builder
  223. */
  224. public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
  225. {
  226. return $query->select($columns)->whereColumn(
  227. $this->getQualifiedParentKeyName(), '=', $this->getExistenceCompareKey()
  228. );
  229. }
  230. /**
  231. * Get a relationship join table hash.
  232. *
  233. * @param bool $incrementJoinCount
  234. * @return string
  235. */
  236. public function getRelationCountHash($incrementJoinCount = true)
  237. {
  238. return 'laravel_reserved_'.($incrementJoinCount ? static::$selfJoinCount++ : static::$selfJoinCount);
  239. }
  240. /**
  241. * Get all of the primary keys for an array of models.
  242. *
  243. * @param array $models
  244. * @param string|null $key
  245. * @return array
  246. */
  247. protected function getKeys(array $models, $key = null)
  248. {
  249. return collect($models)->map(function ($value) use ($key) {
  250. return $key ? $value->getAttribute($key) : $value->getKey();
  251. })->values()->unique(null, true)->sort()->all();
  252. }
  253. /**
  254. * Get the query builder that will contain the relationship constraints.
  255. *
  256. * @return \Illuminate\Database\Eloquent\Builder
  257. */
  258. protected function getRelationQuery()
  259. {
  260. return $this->query;
  261. }
  262. /**
  263. * Get the underlying query for the relation.
  264. *
  265. * @return \Illuminate\Database\Eloquent\Builder
  266. */
  267. public function getQuery()
  268. {
  269. return $this->query;
  270. }
  271. /**
  272. * Get the base query builder driving the Eloquent builder.
  273. *
  274. * @return \Illuminate\Database\Query\Builder
  275. */
  276. public function getBaseQuery()
  277. {
  278. return $this->query->getQuery();
  279. }
  280. /**
  281. * Get a base query builder instance.
  282. *
  283. * @return \Illuminate\Database\Query\Builder
  284. */
  285. public function toBase()
  286. {
  287. return $this->query->toBase();
  288. }
  289. /**
  290. * Get the parent model of the relation.
  291. *
  292. * @return \Illuminate\Database\Eloquent\Model
  293. */
  294. public function getParent()
  295. {
  296. return $this->parent;
  297. }
  298. /**
  299. * Get the fully qualified parent key name.
  300. *
  301. * @return string
  302. */
  303. public function getQualifiedParentKeyName()
  304. {
  305. return $this->parent->getQualifiedKeyName();
  306. }
  307. /**
  308. * Get the related model of the relation.
  309. *
  310. * @return \Illuminate\Database\Eloquent\Model
  311. */
  312. public function getRelated()
  313. {
  314. return $this->related;
  315. }
  316. /**
  317. * Get the name of the "created at" column.
  318. *
  319. * @return string
  320. */
  321. public function createdAt()
  322. {
  323. return $this->parent->getCreatedAtColumn();
  324. }
  325. /**
  326. * Get the name of the "updated at" column.
  327. *
  328. * @return string
  329. */
  330. public function updatedAt()
  331. {
  332. return $this->parent->getUpdatedAtColumn();
  333. }
  334. /**
  335. * Get the name of the related model's "updated at" column.
  336. *
  337. * @return string
  338. */
  339. public function relatedUpdatedAt()
  340. {
  341. return $this->related->getUpdatedAtColumn();
  342. }
  343. /**
  344. * Add a whereIn eager constraint for the given set of model keys to be loaded.
  345. *
  346. * @param string $whereIn
  347. * @param string $key
  348. * @param array $modelKeys
  349. * @param \Illuminate\Database\Eloquent\Builder $query
  350. * @return void
  351. */
  352. protected function whereInEager(string $whereIn, string $key, array $modelKeys, $query = null)
  353. {
  354. ($query ?? $this->query)->{$whereIn}($key, $modelKeys);
  355. if ($modelKeys === []) {
  356. $this->eagerKeysWereEmpty = true;
  357. }
  358. }
  359. /**
  360. * Get the name of the "where in" method for eager loading.
  361. *
  362. * @param \Illuminate\Database\Eloquent\Model $model
  363. * @param string $key
  364. * @return string
  365. */
  366. protected function whereInMethod(Model $model, $key)
  367. {
  368. return $model->getKeyName() === last(explode('.', $key))
  369. && in_array($model->getKeyType(), ['int', 'integer'])
  370. ? 'whereIntegerInRaw'
  371. : 'whereIn';
  372. }
  373. /**
  374. * Prevent polymorphic relationships from being used without model mappings.
  375. *
  376. * @param bool $requireMorphMap
  377. * @return void
  378. */
  379. public static function requireMorphMap($requireMorphMap = true)
  380. {
  381. static::$requireMorphMap = $requireMorphMap;
  382. }
  383. /**
  384. * Determine if polymorphic relationships require explicit model mapping.
  385. *
  386. * @return bool
  387. */
  388. public static function requiresMorphMap()
  389. {
  390. return static::$requireMorphMap;
  391. }
  392. /**
  393. * Define the morph map for polymorphic relations and require all morphed models to be explicitly mapped.
  394. *
  395. * @param array $map
  396. * @param bool $merge
  397. * @return array
  398. */
  399. public static function enforceMorphMap(array $map, $merge = true)
  400. {
  401. static::requireMorphMap();
  402. return static::morphMap($map, $merge);
  403. }
  404. /**
  405. * Set or get the morph map for polymorphic relations.
  406. *
  407. * @param array|null $map
  408. * @param bool $merge
  409. * @return array
  410. */
  411. public static function morphMap(?array $map = null, $merge = true)
  412. {
  413. $map = static::buildMorphMapFromModels($map);
  414. if (is_array($map)) {
  415. static::$morphMap = $merge && static::$morphMap
  416. ? $map + static::$morphMap : $map;
  417. }
  418. return static::$morphMap;
  419. }
  420. /**
  421. * Builds a table-keyed array from model class names.
  422. *
  423. * @param string[]|null $models
  424. * @return array|null
  425. */
  426. protected static function buildMorphMapFromModels(?array $models = null)
  427. {
  428. if (is_null($models) || ! array_is_list($models)) {
  429. return $models;
  430. }
  431. return array_combine(array_map(function ($model) {
  432. return (new $model)->getTable();
  433. }, $models), $models);
  434. }
  435. /**
  436. * Get the model associated with a custom polymorphic type.
  437. *
  438. * @param string $alias
  439. * @return string|null
  440. */
  441. public static function getMorphedModel($alias)
  442. {
  443. return static::$morphMap[$alias] ?? null;
  444. }
  445. /**
  446. * Get the alias associated with a custom polymorphic class.
  447. *
  448. * @param string $className
  449. * @return int|string
  450. */
  451. public static function getMorphAlias(string $className)
  452. {
  453. return array_search($className, static::$morphMap, strict: true) ?: $className;
  454. }
  455. /**
  456. * Handle dynamic method calls to the relationship.
  457. *
  458. * @param string $method
  459. * @param array $parameters
  460. * @return mixed
  461. */
  462. public function __call($method, $parameters)
  463. {
  464. if (static::hasMacro($method)) {
  465. return $this->macroCall($method, $parameters);
  466. }
  467. return $this->forwardDecoratedCallTo($this->query, $method, $parameters);
  468. }
  469. /**
  470. * Force a clone of the underlying query builder when cloning.
  471. *
  472. * @return void
  473. */
  474. public function __clone()
  475. {
  476. $this->query = clone $this->query;
  477. }
  478. }