HasOneOrMany.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Illuminate\Database\Eloquent\Collection;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary;
  7. use Illuminate\Database\UniqueConstraintViolationException;
  8. abstract class HasOneOrMany extends Relation
  9. {
  10. use InteractsWithDictionary;
  11. /**
  12. * The foreign key of the parent model.
  13. *
  14. * @var string
  15. */
  16. protected $foreignKey;
  17. /**
  18. * The local key of the parent model.
  19. *
  20. * @var string
  21. */
  22. protected $localKey;
  23. /**
  24. * Create a new has one or many relationship instance.
  25. *
  26. * @param \Illuminate\Database\Eloquent\Builder $query
  27. * @param \Illuminate\Database\Eloquent\Model $parent
  28. * @param string $foreignKey
  29. * @param string $localKey
  30. * @return void
  31. */
  32. public function __construct(Builder $query, Model $parent, $foreignKey, $localKey)
  33. {
  34. $this->localKey = $localKey;
  35. $this->foreignKey = $foreignKey;
  36. parent::__construct($query, $parent);
  37. }
  38. /**
  39. * Create and return an un-saved instance of the related model.
  40. *
  41. * @param array $attributes
  42. * @return \Illuminate\Database\Eloquent\Model
  43. */
  44. public function make(array $attributes = [])
  45. {
  46. return tap($this->related->newInstance($attributes), function ($instance) {
  47. $this->setForeignAttributesForCreate($instance);
  48. });
  49. }
  50. /**
  51. * Create and return an un-saved instance of the related models.
  52. *
  53. * @param iterable $records
  54. * @return \Illuminate\Database\Eloquent\Collection
  55. */
  56. public function makeMany($records)
  57. {
  58. $instances = $this->related->newCollection();
  59. foreach ($records as $record) {
  60. $instances->push($this->make($record));
  61. }
  62. return $instances;
  63. }
  64. /**
  65. * Set the base constraints on the relation query.
  66. *
  67. * @return void
  68. */
  69. public function addConstraints()
  70. {
  71. if (static::$constraints) {
  72. $query = $this->getRelationQuery();
  73. $query->where($this->foreignKey, '=', $this->getParentKey());
  74. $query->whereNotNull($this->foreignKey);
  75. }
  76. }
  77. /**
  78. * Set the constraints for an eager load of the relation.
  79. *
  80. * @param array $models
  81. * @return void
  82. */
  83. public function addEagerConstraints(array $models)
  84. {
  85. $whereIn = $this->whereInMethod($this->parent, $this->localKey);
  86. $this->whereInEager(
  87. $whereIn,
  88. $this->foreignKey,
  89. $this->getKeys($models, $this->localKey),
  90. $this->getRelationQuery()
  91. );
  92. }
  93. /**
  94. * Match the eagerly loaded results to their single parents.
  95. *
  96. * @param array $models
  97. * @param \Illuminate\Database\Eloquent\Collection $results
  98. * @param string $relation
  99. * @return array
  100. */
  101. public function matchOne(array $models, Collection $results, $relation)
  102. {
  103. return $this->matchOneOrMany($models, $results, $relation, 'one');
  104. }
  105. /**
  106. * Match the eagerly loaded results to their many parents.
  107. *
  108. * @param array $models
  109. * @param \Illuminate\Database\Eloquent\Collection $results
  110. * @param string $relation
  111. * @return array
  112. */
  113. public function matchMany(array $models, Collection $results, $relation)
  114. {
  115. return $this->matchOneOrMany($models, $results, $relation, 'many');
  116. }
  117. /**
  118. * Match the eagerly loaded results to their many parents.
  119. *
  120. * @param array $models
  121. * @param \Illuminate\Database\Eloquent\Collection $results
  122. * @param string $relation
  123. * @param string $type
  124. * @return array
  125. */
  126. protected function matchOneOrMany(array $models, Collection $results, $relation, $type)
  127. {
  128. $dictionary = $this->buildDictionary($results);
  129. // Once we have the dictionary we can simply spin through the parent models to
  130. // link them up with their children using the keyed dictionary to make the
  131. // matching very convenient and easy work. Then we'll just return them.
  132. foreach ($models as $model) {
  133. if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) {
  134. $model->setRelation(
  135. $relation, $this->getRelationValue($dictionary, $key, $type)
  136. );
  137. }
  138. }
  139. return $models;
  140. }
  141. /**
  142. * Get the value of a relationship by one or many type.
  143. *
  144. * @param array $dictionary
  145. * @param string $key
  146. * @param string $type
  147. * @return mixed
  148. */
  149. protected function getRelationValue(array $dictionary, $key, $type)
  150. {
  151. $value = $dictionary[$key];
  152. return $type === 'one' ? reset($value) : $this->related->newCollection($value);
  153. }
  154. /**
  155. * Build model dictionary keyed by the relation's foreign key.
  156. *
  157. * @param \Illuminate\Database\Eloquent\Collection $results
  158. * @return array
  159. */
  160. protected function buildDictionary(Collection $results)
  161. {
  162. $foreign = $this->getForeignKeyName();
  163. return $results->mapToDictionary(function ($result) use ($foreign) {
  164. return [$this->getDictionaryKey($result->{$foreign}) => $result];
  165. })->all();
  166. }
  167. /**
  168. * Find a model by its primary key or return a new instance of the related model.
  169. *
  170. * @param mixed $id
  171. * @param array $columns
  172. * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model
  173. */
  174. public function findOrNew($id, $columns = ['*'])
  175. {
  176. if (is_null($instance = $this->find($id, $columns))) {
  177. $instance = $this->related->newInstance();
  178. $this->setForeignAttributesForCreate($instance);
  179. }
  180. return $instance;
  181. }
  182. /**
  183. * Get the first related model record matching the attributes or instantiate it.
  184. *
  185. * @param array $attributes
  186. * @param array $values
  187. * @return \Illuminate\Database\Eloquent\Model
  188. */
  189. public function firstOrNew(array $attributes = [], array $values = [])
  190. {
  191. if (is_null($instance = $this->where($attributes)->first())) {
  192. $instance = $this->related->newInstance(array_merge($attributes, $values));
  193. $this->setForeignAttributesForCreate($instance);
  194. }
  195. return $instance;
  196. }
  197. /**
  198. * Get the first record matching the attributes. If the record is not found, create it.
  199. *
  200. * @param array $attributes
  201. * @param array $values
  202. * @return \Illuminate\Database\Eloquent\Model
  203. */
  204. public function firstOrCreate(array $attributes = [], array $values = [])
  205. {
  206. if (is_null($instance = (clone $this)->where($attributes)->first())) {
  207. $instance = $this->createOrFirst($attributes, $values);
  208. }
  209. return $instance;
  210. }
  211. /**
  212. * Attempt to create the record. If a unique constraint violation occurs, attempt to find the matching record.
  213. *
  214. * @param array $attributes
  215. * @param array $values
  216. * @return \Illuminate\Database\Eloquent\Model
  217. */
  218. public function createOrFirst(array $attributes = [], array $values = [])
  219. {
  220. try {
  221. return $this->getQuery()->withSavepointIfNeeded(fn () => $this->create(array_merge($attributes, $values)));
  222. } catch (UniqueConstraintViolationException $e) {
  223. return $this->useWritePdo()->where($attributes)->first() ?? throw $e;
  224. }
  225. }
  226. /**
  227. * Create or update a related record matching the attributes, and fill it with values.
  228. *
  229. * @param array $attributes
  230. * @param array $values
  231. * @return \Illuminate\Database\Eloquent\Model
  232. */
  233. public function updateOrCreate(array $attributes, array $values = [])
  234. {
  235. return tap($this->firstOrCreate($attributes, $values), function ($instance) use ($values) {
  236. if (! $instance->wasRecentlyCreated) {
  237. $instance->fill($values)->save();
  238. }
  239. });
  240. }
  241. /**
  242. * Attach a model instance to the parent model.
  243. *
  244. * @param \Illuminate\Database\Eloquent\Model $model
  245. * @return \Illuminate\Database\Eloquent\Model|false
  246. */
  247. public function save(Model $model)
  248. {
  249. $this->setForeignAttributesForCreate($model);
  250. return $model->save() ? $model : false;
  251. }
  252. /**
  253. * Attach a model instance without raising any events to the parent model.
  254. *
  255. * @param \Illuminate\Database\Eloquent\Model $model
  256. * @return \Illuminate\Database\Eloquent\Model|false
  257. */
  258. public function saveQuietly(Model $model)
  259. {
  260. return Model::withoutEvents(function () use ($model) {
  261. return $this->save($model);
  262. });
  263. }
  264. /**
  265. * Attach a collection of models to the parent instance.
  266. *
  267. * @param iterable $models
  268. * @return iterable
  269. */
  270. public function saveMany($models)
  271. {
  272. foreach ($models as $model) {
  273. $this->save($model);
  274. }
  275. return $models;
  276. }
  277. /**
  278. * Attach a collection of models to the parent instance without raising any events to the parent model.
  279. *
  280. * @param iterable $models
  281. * @return iterable
  282. */
  283. public function saveManyQuietly($models)
  284. {
  285. return Model::withoutEvents(function () use ($models) {
  286. return $this->saveMany($models);
  287. });
  288. }
  289. /**
  290. * Create a new instance of the related model.
  291. *
  292. * @param array $attributes
  293. * @return \Illuminate\Database\Eloquent\Model
  294. */
  295. public function create(array $attributes = [])
  296. {
  297. return tap($this->related->newInstance($attributes), function ($instance) {
  298. $this->setForeignAttributesForCreate($instance);
  299. $instance->save();
  300. });
  301. }
  302. /**
  303. * Create a new instance of the related model without raising any events to the parent model.
  304. *
  305. * @param array $attributes
  306. * @return \Illuminate\Database\Eloquent\Model
  307. */
  308. public function createQuietly(array $attributes = [])
  309. {
  310. return Model::withoutEvents(fn () => $this->create($attributes));
  311. }
  312. /**
  313. * Create a new instance of the related model. Allow mass-assignment.
  314. *
  315. * @param array $attributes
  316. * @return \Illuminate\Database\Eloquent\Model
  317. */
  318. public function forceCreate(array $attributes = [])
  319. {
  320. $attributes[$this->getForeignKeyName()] = $this->getParentKey();
  321. return $this->related->forceCreate($attributes);
  322. }
  323. /**
  324. * Create a new instance of the related model with mass assignment without raising model events.
  325. *
  326. * @param array $attributes
  327. * @return \Illuminate\Database\Eloquent\Model
  328. */
  329. public function forceCreateQuietly(array $attributes = [])
  330. {
  331. return Model::withoutEvents(fn () => $this->forceCreate($attributes));
  332. }
  333. /**
  334. * Create a Collection of new instances of the related model.
  335. *
  336. * @param iterable $records
  337. * @return \Illuminate\Database\Eloquent\Collection
  338. */
  339. public function createMany(iterable $records)
  340. {
  341. $instances = $this->related->newCollection();
  342. foreach ($records as $record) {
  343. $instances->push($this->create($record));
  344. }
  345. return $instances;
  346. }
  347. /**
  348. * Create a Collection of new instances of the related model without raising any events to the parent model.
  349. *
  350. * @param iterable $records
  351. * @return \Illuminate\Database\Eloquent\Collection
  352. */
  353. public function createManyQuietly(iterable $records)
  354. {
  355. return Model::withoutEvents(fn () => $this->createMany($records));
  356. }
  357. /**
  358. * Set the foreign ID for creating a related model.
  359. *
  360. * @param \Illuminate\Database\Eloquent\Model $model
  361. * @return void
  362. */
  363. protected function setForeignAttributesForCreate(Model $model)
  364. {
  365. $model->setAttribute($this->getForeignKeyName(), $this->getParentKey());
  366. }
  367. /**
  368. * Add the constraints for a relationship query.
  369. *
  370. * @param \Illuminate\Database\Eloquent\Builder $query
  371. * @param \Illuminate\Database\Eloquent\Builder $parentQuery
  372. * @param array|mixed $columns
  373. * @return \Illuminate\Database\Eloquent\Builder
  374. */
  375. public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
  376. {
  377. if ($query->getQuery()->from == $parentQuery->getQuery()->from) {
  378. return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
  379. }
  380. return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
  381. }
  382. /**
  383. * Add the constraints for a relationship query on the same table.
  384. *
  385. * @param \Illuminate\Database\Eloquent\Builder $query
  386. * @param \Illuminate\Database\Eloquent\Builder $parentQuery
  387. * @param array|mixed $columns
  388. * @return \Illuminate\Database\Eloquent\Builder
  389. */
  390. public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
  391. {
  392. $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());
  393. $query->getModel()->setTable($hash);
  394. return $query->select($columns)->whereColumn(
  395. $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->getForeignKeyName()
  396. );
  397. }
  398. /**
  399. * Alias to set the "limit" value of the query.
  400. *
  401. * @param int $value
  402. * @return $this
  403. */
  404. public function take($value)
  405. {
  406. return $this->limit($value);
  407. }
  408. /**
  409. * Set the "limit" value of the query.
  410. *
  411. * @param int $value
  412. * @return $this
  413. */
  414. public function limit($value)
  415. {
  416. if ($this->parent->exists) {
  417. $this->query->limit($value);
  418. } else {
  419. $this->query->groupLimit($value, $this->getExistenceCompareKey());
  420. }
  421. return $this;
  422. }
  423. /**
  424. * Get the key for comparing against the parent key in "has" query.
  425. *
  426. * @return string
  427. */
  428. public function getExistenceCompareKey()
  429. {
  430. return $this->getQualifiedForeignKeyName();
  431. }
  432. /**
  433. * Get the key value of the parent's local key.
  434. *
  435. * @return mixed
  436. */
  437. public function getParentKey()
  438. {
  439. return $this->parent->getAttribute($this->localKey);
  440. }
  441. /**
  442. * Get the fully qualified parent key name.
  443. *
  444. * @return string
  445. */
  446. public function getQualifiedParentKeyName()
  447. {
  448. return $this->parent->qualifyColumn($this->localKey);
  449. }
  450. /**
  451. * Get the plain foreign key.
  452. *
  453. * @return string
  454. */
  455. public function getForeignKeyName()
  456. {
  457. $segments = explode('.', $this->getQualifiedForeignKeyName());
  458. return end($segments);
  459. }
  460. /**
  461. * Get the foreign key for the relationship.
  462. *
  463. * @return string
  464. */
  465. public function getQualifiedForeignKeyName()
  466. {
  467. return $this->foreignKey;
  468. }
  469. /**
  470. * Get the local key for the relationship.
  471. *
  472. * @return string
  473. */
  474. public function getLocalKeyName()
  475. {
  476. return $this->localKey;
  477. }
  478. }