BelongsToMany.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations;
  3. use Illuminate\Support\Str;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Builder;
  6. use Illuminate\Database\Eloquent\Collection;
  7. use Illuminate\Database\Eloquent\ModelNotFoundException;
  8. class BelongsToMany extends Relation
  9. {
  10. use Concerns\InteractsWithPivotTable;
  11. /**
  12. * The intermediate table for the relation.
  13. *
  14. * @var string
  15. */
  16. protected $table;
  17. /**
  18. * The foreign key of the parent model.
  19. *
  20. * @var string
  21. */
  22. protected $foreignPivotKey;
  23. /**
  24. * The associated key of the relation.
  25. *
  26. * @var string
  27. */
  28. protected $relatedPivotKey;
  29. /**
  30. * The key name of the parent model.
  31. *
  32. * @var string
  33. */
  34. protected $parentKey;
  35. /**
  36. * The key name of the related model.
  37. *
  38. * @var string
  39. */
  40. protected $relatedKey;
  41. /**
  42. * The "name" of the relationship.
  43. *
  44. * @var string
  45. */
  46. protected $relationName;
  47. /**
  48. * The pivot table columns to retrieve.
  49. *
  50. * @var array
  51. */
  52. protected $pivotColumns = [];
  53. /**
  54. * Any pivot table restrictions for where clauses.
  55. *
  56. * @var array
  57. */
  58. protected $pivotWheres = [];
  59. /**
  60. * Any pivot table restrictions for whereIn clauses.
  61. *
  62. * @var array
  63. */
  64. protected $pivotWhereIns = [];
  65. /**
  66. * Indicates if timestamps are available on the pivot table.
  67. *
  68. * @var bool
  69. */
  70. public $withTimestamps = false;
  71. /**
  72. * The custom pivot table column for the created_at timestamp.
  73. *
  74. * @var string
  75. */
  76. protected $pivotCreatedAt;
  77. /**
  78. * The custom pivot table column for the updated_at timestamp.
  79. *
  80. * @var string
  81. */
  82. protected $pivotUpdatedAt;
  83. /**
  84. * The class name of the custom pivot model to use for the relationship.
  85. *
  86. * @var string
  87. */
  88. protected $using;
  89. /**
  90. * The name of the accessor to use for the "pivot" relationship.
  91. *
  92. * @var string
  93. */
  94. protected $accessor = 'pivot';
  95. /**
  96. * The count of self joins.
  97. *
  98. * @var int
  99. */
  100. protected static $selfJoinCount = 0;
  101. /**
  102. * Create a new belongs to many relationship instance.
  103. *
  104. * @param \Illuminate\Database\Eloquent\Builder $query
  105. * @param \Illuminate\Database\Eloquent\Model $parent
  106. * @param string $table
  107. * @param string $foreignPivotKey
  108. * @param string $relatedPivotKey
  109. * @param string $parentKey
  110. * @param string $relatedKey
  111. * @param string $relationName
  112. * @return void
  113. */
  114. public function __construct(Builder $query, Model $parent, $table, $foreignPivotKey,
  115. $relatedPivotKey, $parentKey, $relatedKey, $relationName = null)
  116. {
  117. $this->table = $table;
  118. $this->parentKey = $parentKey;
  119. $this->relatedKey = $relatedKey;
  120. $this->relationName = $relationName;
  121. $this->relatedPivotKey = $relatedPivotKey;
  122. $this->foreignPivotKey = $foreignPivotKey;
  123. parent::__construct($query, $parent);
  124. }
  125. /**
  126. * Set the base constraints on the relation query.
  127. *
  128. * @return void
  129. */
  130. public function addConstraints()
  131. {
  132. $this->performJoin();
  133. if (static::$constraints) {
  134. $this->addWhereConstraints();
  135. }
  136. }
  137. /**
  138. * Set the join clause for the relation query.
  139. *
  140. * @param \Illuminate\Database\Eloquent\Builder|null $query
  141. * @return $this
  142. */
  143. protected function performJoin($query = null)
  144. {
  145. $query = $query ?: $this->query;
  146. // We need to join to the intermediate table on the related model's primary
  147. // key column with the intermediate table's foreign key for the related
  148. // model instance. Then we can set the "where" for the parent models.
  149. $baseTable = $this->related->getTable();
  150. $key = $baseTable.'.'.$this->relatedKey;
  151. $query->join($this->table, $key, '=', $this->getQualifiedRelatedPivotKeyName());
  152. return $this;
  153. }
  154. /**
  155. * Set the where clause for the relation query.
  156. *
  157. * @return $this
  158. */
  159. protected function addWhereConstraints()
  160. {
  161. $this->query->where(
  162. $this->getQualifiedForeignPivotKeyName(), '=', $this->parent->{$this->parentKey}
  163. );
  164. return $this;
  165. }
  166. /**
  167. * Set the constraints for an eager load of the relation.
  168. *
  169. * @param array $models
  170. * @return void
  171. */
  172. public function addEagerConstraints(array $models)
  173. {
  174. $this->query->whereIn($this->getQualifiedForeignPivotKeyName(), $this->getKeys($models, $this->parentKey));
  175. }
  176. /**
  177. * Initialize the relation on a set of models.
  178. *
  179. * @param array $models
  180. * @param string $relation
  181. * @return array
  182. */
  183. public function initRelation(array $models, $relation)
  184. {
  185. foreach ($models as $model) {
  186. $model->setRelation($relation, $this->related->newCollection());
  187. }
  188. return $models;
  189. }
  190. /**
  191. * Match the eagerly loaded results to their parents.
  192. *
  193. * @param array $models
  194. * @param \Illuminate\Database\Eloquent\Collection $results
  195. * @param string $relation
  196. * @return array
  197. */
  198. public function match(array $models, Collection $results, $relation)
  199. {
  200. $dictionary = $this->buildDictionary($results);
  201. // Once we have an array dictionary of child objects we can easily match the
  202. // children back to their parent using the dictionary and the keys on the
  203. // the parent models. Then we will return the hydrated models back out.
  204. foreach ($models as $model) {
  205. if (isset($dictionary[$key = $model->{$this->parentKey}])) {
  206. $model->setRelation(
  207. $relation, $this->related->newCollection($dictionary[$key])
  208. );
  209. }
  210. }
  211. return $models;
  212. }
  213. /**
  214. * Build model dictionary keyed by the relation's foreign key.
  215. *
  216. * @param \Illuminate\Database\Eloquent\Collection $results
  217. * @return array
  218. */
  219. protected function buildDictionary(Collection $results)
  220. {
  221. // First we will build a dictionary of child models keyed by the foreign key
  222. // of the relation so that we will easily and quickly match them to their
  223. // parents without having a possibly slow inner loops for every models.
  224. $dictionary = [];
  225. foreach ($results as $result) {
  226. $dictionary[$result->{$this->accessor}->{$this->foreignPivotKey}][] = $result;
  227. }
  228. return $dictionary;
  229. }
  230. /**
  231. * Specify the custom pivot model to use for the relationship.
  232. *
  233. * @param string $class
  234. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  235. */
  236. public function using($class)
  237. {
  238. $this->using = $class;
  239. return $this;
  240. }
  241. /**
  242. * Specify the custom pivot accessor to use for the relationship.
  243. *
  244. * @param string $accessor
  245. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  246. */
  247. public function as($accessor)
  248. {
  249. $this->accessor = $accessor;
  250. return $this;
  251. }
  252. /**
  253. * Set a where clause for a pivot table column.
  254. *
  255. * @param string $column
  256. * @param string $operator
  257. * @param mixed $value
  258. * @param string $boolean
  259. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  260. */
  261. public function wherePivot($column, $operator = null, $value = null, $boolean = 'and')
  262. {
  263. $this->pivotWheres[] = func_get_args();
  264. return $this->where($this->table.'.'.$column, $operator, $value, $boolean);
  265. }
  266. /**
  267. * Set a "where in" clause for a pivot table column.
  268. *
  269. * @param string $column
  270. * @param mixed $values
  271. * @param string $boolean
  272. * @param bool $not
  273. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  274. */
  275. public function wherePivotIn($column, $values, $boolean = 'and', $not = false)
  276. {
  277. $this->pivotWhereIns[] = func_get_args();
  278. return $this->whereIn($this->table.'.'.$column, $values, $boolean, $not);
  279. }
  280. /**
  281. * Set an "or where" clause for a pivot table column.
  282. *
  283. * @param string $column
  284. * @param string $operator
  285. * @param mixed $value
  286. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  287. */
  288. public function orWherePivot($column, $operator = null, $value = null)
  289. {
  290. return $this->wherePivot($column, $operator, $value, 'or');
  291. }
  292. /**
  293. * Set an "or where in" clause for a pivot table column.
  294. *
  295. * @param string $column
  296. * @param mixed $values
  297. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  298. */
  299. public function orWherePivotIn($column, $values)
  300. {
  301. return $this->wherePivotIn($column, $values, 'or');
  302. }
  303. /**
  304. * Find a related model by its primary key or return new instance of the related model.
  305. *
  306. * @param mixed $id
  307. * @param array $columns
  308. * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model
  309. */
  310. public function findOrNew($id, $columns = ['*'])
  311. {
  312. if (is_null($instance = $this->find($id, $columns))) {
  313. $instance = $this->related->newInstance();
  314. }
  315. return $instance;
  316. }
  317. /**
  318. * Get the first related model record matching the attributes or instantiate it.
  319. *
  320. * @param array $attributes
  321. * @return \Illuminate\Database\Eloquent\Model
  322. */
  323. public function firstOrNew(array $attributes)
  324. {
  325. if (is_null($instance = $this->where($attributes)->first())) {
  326. $instance = $this->related->newInstance($attributes);
  327. }
  328. return $instance;
  329. }
  330. /**
  331. * Get the first related record matching the attributes or create it.
  332. *
  333. * @param array $attributes
  334. * @param array $joining
  335. * @param bool $touch
  336. * @return \Illuminate\Database\Eloquent\Model
  337. */
  338. public function firstOrCreate(array $attributes, array $joining = [], $touch = true)
  339. {
  340. if (is_null($instance = $this->where($attributes)->first())) {
  341. $instance = $this->create($attributes, $joining, $touch);
  342. }
  343. return $instance;
  344. }
  345. /**
  346. * Create or update a related record matching the attributes, and fill it with values.
  347. *
  348. * @param array $attributes
  349. * @param array $values
  350. * @param array $joining
  351. * @param bool $touch
  352. * @return \Illuminate\Database\Eloquent\Model
  353. */
  354. public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true)
  355. {
  356. if (is_null($instance = $this->where($attributes)->first())) {
  357. return $this->create($values, $joining, $touch);
  358. }
  359. $instance->fill($values);
  360. $instance->save(['touch' => false]);
  361. return $instance;
  362. }
  363. /**
  364. * Find a related model by its primary key.
  365. *
  366. * @param mixed $id
  367. * @param array $columns
  368. * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null
  369. */
  370. public function find($id, $columns = ['*'])
  371. {
  372. return is_array($id) ? $this->findMany($id, $columns) : $this->where(
  373. $this->getRelated()->getQualifiedKeyName(), '=', $id
  374. )->first($columns);
  375. }
  376. /**
  377. * Find multiple related models by their primary keys.
  378. *
  379. * @param mixed $ids
  380. * @param array $columns
  381. * @return \Illuminate\Database\Eloquent\Collection
  382. */
  383. public function findMany($ids, $columns = ['*'])
  384. {
  385. return empty($ids) ? $this->getRelated()->newCollection() : $this->whereIn(
  386. $this->getRelated()->getQualifiedKeyName(), $ids
  387. )->get($columns);
  388. }
  389. /**
  390. * Find a related model by its primary key or throw an exception.
  391. *
  392. * @param mixed $id
  393. * @param array $columns
  394. * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
  395. *
  396. * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
  397. */
  398. public function findOrFail($id, $columns = ['*'])
  399. {
  400. $result = $this->find($id, $columns);
  401. if (is_array($id)) {
  402. if (count($result) == count(array_unique($id))) {
  403. return $result;
  404. }
  405. } elseif (! is_null($result)) {
  406. return $result;
  407. }
  408. throw (new ModelNotFoundException)->setModel(get_class($this->related));
  409. }
  410. /**
  411. * Execute the query and get the first result.
  412. *
  413. * @param array $columns
  414. * @return mixed
  415. */
  416. public function first($columns = ['*'])
  417. {
  418. $results = $this->take(1)->get($columns);
  419. return count($results) > 0 ? $results->first() : null;
  420. }
  421. /**
  422. * Execute the query and get the first result or throw an exception.
  423. *
  424. * @param array $columns
  425. * @return \Illuminate\Database\Eloquent\Model|static
  426. *
  427. * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
  428. */
  429. public function firstOrFail($columns = ['*'])
  430. {
  431. if (! is_null($model = $this->first($columns))) {
  432. return $model;
  433. }
  434. throw (new ModelNotFoundException)->setModel(get_class($this->related));
  435. }
  436. /**
  437. * Get the results of the relationship.
  438. *
  439. * @return mixed
  440. */
  441. public function getResults()
  442. {
  443. return $this->get();
  444. }
  445. /**
  446. * Execute the query as a "select" statement.
  447. *
  448. * @param array $columns
  449. * @return \Illuminate\Database\Eloquent\Collection
  450. */
  451. public function get($columns = ['*'])
  452. {
  453. // First we'll add the proper select columns onto the query so it is run with
  454. // the proper columns. Then, we will get the results and hydrate out pivot
  455. // models with the result of those columns as a separate model relation.
  456. $columns = $this->query->getQuery()->columns ? [] : $columns;
  457. $builder = $this->query->applyScopes();
  458. $models = $builder->addSelect(
  459. $this->shouldSelect($columns)
  460. )->getModels();
  461. $this->hydratePivotRelation($models);
  462. // If we actually found models we will also eager load any relationships that
  463. // have been specified as needing to be eager loaded. This will solve the
  464. // n + 1 query problem for the developer and also increase performance.
  465. if (count($models) > 0) {
  466. $models = $builder->eagerLoadRelations($models);
  467. }
  468. return $this->related->newCollection($models);
  469. }
  470. /**
  471. * Get the select columns for the relation query.
  472. *
  473. * @param array $columns
  474. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  475. */
  476. protected function shouldSelect(array $columns = ['*'])
  477. {
  478. if ($columns == ['*']) {
  479. $columns = [$this->related->getTable().'.*'];
  480. }
  481. return array_merge($columns, $this->aliasedPivotColumns());
  482. }
  483. /**
  484. * Get the pivot columns for the relation.
  485. *
  486. * "pivot_" is prefixed ot each column for easy removal later.
  487. *
  488. * @return array
  489. */
  490. protected function aliasedPivotColumns()
  491. {
  492. $defaults = [$this->foreignPivotKey, $this->relatedPivotKey];
  493. return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) {
  494. return $this->table.'.'.$column.' as pivot_'.$column;
  495. })->unique()->all();
  496. }
  497. /**
  498. * Get a paginator for the "select" statement.
  499. *
  500. * @param int $perPage
  501. * @param array $columns
  502. * @param string $pageName
  503. * @param int|null $page
  504. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  505. */
  506. public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
  507. {
  508. $this->query->addSelect($this->shouldSelect($columns));
  509. return tap($this->query->paginate($perPage, $columns, $pageName, $page), function ($paginator) {
  510. $this->hydratePivotRelation($paginator->items());
  511. });
  512. }
  513. /**
  514. * Paginate the given query into a simple paginator.
  515. *
  516. * @param int $perPage
  517. * @param array $columns
  518. * @param string $pageName
  519. * @param int|null $page
  520. * @return \Illuminate\Contracts\Pagination\Paginator
  521. */
  522. public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
  523. {
  524. $this->query->addSelect($this->shouldSelect($columns));
  525. return tap($this->query->simplePaginate($perPage, $columns, $pageName, $page), function ($paginator) {
  526. $this->hydratePivotRelation($paginator->items());
  527. });
  528. }
  529. /**
  530. * Chunk the results of the query.
  531. *
  532. * @param int $count
  533. * @param callable $callback
  534. * @return bool
  535. */
  536. public function chunk($count, callable $callback)
  537. {
  538. $this->query->addSelect($this->shouldSelect());
  539. return $this->query->chunk($count, function ($results) use ($callback) {
  540. $this->hydratePivotRelation($results->all());
  541. return $callback($results);
  542. });
  543. }
  544. /**
  545. * Hydrate the pivot table relationship on the models.
  546. *
  547. * @param array $models
  548. * @return void
  549. */
  550. protected function hydratePivotRelation(array $models)
  551. {
  552. // To hydrate the pivot relationship, we will just gather the pivot attributes
  553. // and create a new Pivot model, which is basically a dynamic model that we
  554. // will set the attributes, table, and connections on it so it will work.
  555. foreach ($models as $model) {
  556. $model->setRelation($this->accessor, $this->newExistingPivot(
  557. $this->migratePivotAttributes($model)
  558. ));
  559. }
  560. }
  561. /**
  562. * Get the pivot attributes from a model.
  563. *
  564. * @param \Illuminate\Database\Eloquent\Model $model
  565. * @return array
  566. */
  567. protected function migratePivotAttributes(Model $model)
  568. {
  569. $values = [];
  570. foreach ($model->getAttributes() as $key => $value) {
  571. // To get the pivots attributes we will just take any of the attributes which
  572. // begin with "pivot_" and add those to this arrays, as well as unsetting
  573. // them from the parent's models since they exist in a different table.
  574. if (strpos($key, 'pivot_') === 0) {
  575. $values[substr($key, 6)] = $value;
  576. unset($model->$key);
  577. }
  578. }
  579. return $values;
  580. }
  581. /**
  582. * If we're touching the parent model, touch.
  583. *
  584. * @return void
  585. */
  586. public function touchIfTouching()
  587. {
  588. if ($this->touchingParent()) {
  589. $this->getParent()->touch();
  590. }
  591. if ($this->getParent()->touches($this->relationName)) {
  592. $this->touch();
  593. }
  594. }
  595. /**
  596. * Determine if we should touch the parent on sync.
  597. *
  598. * @return bool
  599. */
  600. protected function touchingParent()
  601. {
  602. return $this->getRelated()->touches($this->guessInverseRelation());
  603. }
  604. /**
  605. * Attempt to guess the name of the inverse of the relation.
  606. *
  607. * @return string
  608. */
  609. protected function guessInverseRelation()
  610. {
  611. return Str::camel(Str::plural(class_basename($this->getParent())));
  612. }
  613. /**
  614. * Touch all of the related models for the relationship.
  615. *
  616. * E.g.: Touch all roles associated with this user.
  617. *
  618. * @return void
  619. */
  620. public function touch()
  621. {
  622. $key = $this->getRelated()->getKeyName();
  623. $columns = [
  624. $this->related->getUpdatedAtColumn() => $this->related->freshTimestampString(),
  625. ];
  626. // If we actually have IDs for the relation, we will run the query to update all
  627. // the related model's timestamps, to make sure these all reflect the changes
  628. // to the parent models. This will help us keep any caching synced up here.
  629. if (count($ids = $this->allRelatedIds()) > 0) {
  630. $this->getRelated()->newQuery()->whereIn($key, $ids)->update($columns);
  631. }
  632. }
  633. /**
  634. * Get all of the IDs for the related models.
  635. *
  636. * @return \Illuminate\Support\Collection
  637. */
  638. public function allRelatedIds()
  639. {
  640. return $this->newPivotQuery()->pluck($this->relatedPivotKey);
  641. }
  642. /**
  643. * Save a new model and attach it to the parent model.
  644. *
  645. * @param \Illuminate\Database\Eloquent\Model $model
  646. * @param array $pivotAttributes
  647. * @param bool $touch
  648. * @return \Illuminate\Database\Eloquent\Model
  649. */
  650. public function save(Model $model, array $pivotAttributes = [], $touch = true)
  651. {
  652. $model->save(['touch' => false]);
  653. $this->attach($model->getKey(), $pivotAttributes, $touch);
  654. return $model;
  655. }
  656. /**
  657. * Save an array of new models and attach them to the parent model.
  658. *
  659. * @param \Illuminate\Support\Collection|array $models
  660. * @param array $pivotAttributes
  661. * @return array
  662. */
  663. public function saveMany($models, array $pivotAttributes = [])
  664. {
  665. foreach ($models as $key => $model) {
  666. $this->save($model, (array) ($pivotAttributes[$key] ?? []), false);
  667. }
  668. $this->touchIfTouching();
  669. return $models;
  670. }
  671. /**
  672. * Create a new instance of the related model.
  673. *
  674. * @param array $attributes
  675. * @param array $joining
  676. * @param bool $touch
  677. * @return \Illuminate\Database\Eloquent\Model
  678. */
  679. public function create(array $attributes = [], array $joining = [], $touch = true)
  680. {
  681. $instance = $this->related->newInstance($attributes);
  682. // Once we save the related model, we need to attach it to the base model via
  683. // through intermediate table so we'll use the existing "attach" method to
  684. // accomplish this which will insert the record and any more attributes.
  685. $instance->save(['touch' => false]);
  686. $this->attach($instance->getKey(), $joining, $touch);
  687. return $instance;
  688. }
  689. /**
  690. * Create an array of new instances of the related models.
  691. *
  692. * @param array $records
  693. * @param array $joinings
  694. * @return array
  695. */
  696. public function createMany(array $records, array $joinings = [])
  697. {
  698. $instances = [];
  699. foreach ($records as $key => $record) {
  700. $instances[] = $this->create($record, (array) ($joinings[$key] ?? []), false);
  701. }
  702. $this->touchIfTouching();
  703. return $instances;
  704. }
  705. /**
  706. * Add the constraints for a relationship query.
  707. *
  708. * @param \Illuminate\Database\Eloquent\Builder $query
  709. * @param \Illuminate\Database\Eloquent\Builder $parentQuery
  710. * @param array|mixed $columns
  711. * @return \Illuminate\Database\Eloquent\Builder
  712. */
  713. public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
  714. {
  715. if ($parentQuery->getQuery()->from == $query->getQuery()->from) {
  716. return $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns);
  717. }
  718. $this->performJoin($query);
  719. return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
  720. }
  721. /**
  722. * Add the constraints for a relationship query on the same table.
  723. *
  724. * @param \Illuminate\Database\Eloquent\Builder $query
  725. * @param \Illuminate\Database\Eloquent\Builder $parentQuery
  726. * @param array|mixed $columns
  727. * @return \Illuminate\Database\Eloquent\Builder
  728. */
  729. public function getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, $columns = ['*'])
  730. {
  731. $query->select($columns);
  732. $query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash());
  733. $this->related->setTable($hash);
  734. $this->performJoin($query);
  735. return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
  736. }
  737. /**
  738. * Get the key for comparing against the parent key in "has" query.
  739. *
  740. * @return string
  741. */
  742. public function getExistenceCompareKey()
  743. {
  744. return $this->getQualifiedForeignPivotKeyName();
  745. }
  746. /**
  747. * Get a relationship join table hash.
  748. *
  749. * @return string
  750. */
  751. public function getRelationCountHash()
  752. {
  753. return 'laravel_reserved_'.static::$selfJoinCount++;
  754. }
  755. /**
  756. * Specify that the pivot table has creation and update timestamps.
  757. *
  758. * @param mixed $createdAt
  759. * @param mixed $updatedAt
  760. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  761. */
  762. public function withTimestamps($createdAt = null, $updatedAt = null)
  763. {
  764. $this->withTimestamps = true;
  765. $this->pivotCreatedAt = $createdAt;
  766. $this->pivotUpdatedAt = $updatedAt;
  767. return $this->withPivot($this->createdAt(), $this->updatedAt());
  768. }
  769. /**
  770. * Get the name of the "created at" column.
  771. *
  772. * @return string
  773. */
  774. public function createdAt()
  775. {
  776. return $this->pivotCreatedAt ?: $this->parent->getCreatedAtColumn();
  777. }
  778. /**
  779. * Get the name of the "updated at" column.
  780. *
  781. * @return string
  782. */
  783. public function updatedAt()
  784. {
  785. return $this->pivotUpdatedAt ?: $this->parent->getUpdatedAtColumn();
  786. }
  787. /**
  788. * Get the foreign key for the relation.
  789. *
  790. * @return string
  791. */
  792. public function getForeignPivotKeyName()
  793. {
  794. return $this->foreignPivotKey;
  795. }
  796. /**
  797. * Get the fully qualified foreign key for the relation.
  798. *
  799. * @return string
  800. */
  801. public function getQualifiedForeignPivotKeyName()
  802. {
  803. return $this->table.'.'.$this->foreignPivotKey;
  804. }
  805. /**
  806. * Get the "related key" for the relation.
  807. *
  808. * @return string
  809. */
  810. public function getRelatedPivotKeyName()
  811. {
  812. return $this->relatedPivotKey;
  813. }
  814. /**
  815. * Get the fully qualified "related key" for the relation.
  816. *
  817. * @return string
  818. */
  819. public function getQualifiedRelatedPivotKeyName()
  820. {
  821. return $this->table.'.'.$this->relatedPivotKey;
  822. }
  823. /**
  824. * Get the fully qualified parent key name for the relation.
  825. *
  826. * @return string
  827. */
  828. public function getQualifiedParentKeyName()
  829. {
  830. return $this->parent->qualifyColumn($this->parentKey);
  831. }
  832. /**
  833. * Get the intermediate table for the relationship.
  834. *
  835. * @return string
  836. */
  837. public function getTable()
  838. {
  839. return $this->table;
  840. }
  841. /**
  842. * Get the relationship name for the relationship.
  843. *
  844. * @return string
  845. */
  846. public function getRelationName()
  847. {
  848. return $this->relationName;
  849. }
  850. /**
  851. * Get the name of the pivot accessor for this relationship.
  852. *
  853. * @return string
  854. */
  855. public function getPivotAccessor()
  856. {
  857. return $this->accessor;
  858. }
  859. }