EloquentRepository.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. <?php
  2. namespace Dcat\Admin\Repositories;
  3. use Dcat\Admin\Contracts\TreeRepository;
  4. use Dcat\Admin\Exception\AdminException;
  5. use Dcat\Admin\Exception\RuntimeException;
  6. use Dcat\Admin\Form;
  7. use Dcat\Admin\Grid;
  8. use Dcat\Admin\Show;
  9. use Dcat\Laravel\Database\SoftDeletes as DcatSoftDeletes;
  10. use Illuminate\Database\Eloquent\Builder;
  11. use Illuminate\Database\Eloquent\Model as EloquentModel;
  12. use Illuminate\Database\Eloquent\Relations;
  13. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  14. use Illuminate\Database\Eloquent\Relations\HasOne;
  15. use Illuminate\Database\Eloquent\Relations\Relation;
  16. use Illuminate\Database\Eloquent\SoftDeletes;
  17. use Illuminate\Support\Arr;
  18. use Illuminate\Support\Collection;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Str;
  21. use Spatie\EloquentSortable\Sortable;
  22. class EloquentRepository extends Repository implements TreeRepository
  23. {
  24. /**
  25. * @var string
  26. */
  27. protected $eloquentClass;
  28. /**
  29. * @var EloquentModel
  30. */
  31. protected $model;
  32. /**
  33. * @var Builder
  34. */
  35. protected $queryBuilder;
  36. /**
  37. * @var array
  38. */
  39. protected $relations = [];
  40. /**
  41. * @var \Illuminate\Database\Eloquent\Collection
  42. */
  43. protected $collection;
  44. /**
  45. * EloquentRepository constructor.
  46. *
  47. * @param EloquentModel|array|string $modelOrRelations $modelOrRelations
  48. */
  49. public function __construct($modelOrRelations = [])
  50. {
  51. $this->initModel($modelOrRelations);
  52. }
  53. /**
  54. * 初始化模型.
  55. *
  56. * @param EloquentModel|Builder|array|string $modelOrRelations
  57. */
  58. protected function initModel($modelOrRelations)
  59. {
  60. if (is_string($modelOrRelations) && class_exists($modelOrRelations)) {
  61. $this->eloquentClass = $modelOrRelations;
  62. } elseif ($modelOrRelations instanceof EloquentModel) {
  63. $this->eloquentClass = get_class($modelOrRelations);
  64. $this->model = $modelOrRelations;
  65. } elseif ($modelOrRelations instanceof Builder) {
  66. $this->model = $modelOrRelations->getModel();
  67. $this->eloquentClass = get_class($this->model);
  68. $this->queryBuilder = $modelOrRelations;
  69. } else {
  70. $this->setRelations($modelOrRelations);
  71. }
  72. $this->setKeyName($this->model()->getKeyName());
  73. $traits = class_uses($this->model());
  74. $this->setIsSoftDeletes(
  75. in_array(SoftDeletes::class, $traits, true)
  76. || in_array(DcatSoftDeletes::class, $traits, true)
  77. );
  78. }
  79. /**
  80. * @return string
  81. */
  82. public function getCreatedAtColumn()
  83. {
  84. return $this->model()->getCreatedAtColumn();
  85. }
  86. /**
  87. * @return string
  88. */
  89. public function getUpdatedAtColumn()
  90. {
  91. return $this->model()->getUpdatedAtColumn();
  92. }
  93. /**
  94. * 获取列表页面查询的字段.
  95. *
  96. * @return array
  97. */
  98. public function getGridColumns()
  99. {
  100. return ['*'];
  101. }
  102. /**
  103. * 获取表单页面查询的字段.
  104. *
  105. * @return array
  106. */
  107. public function getFormColumns()
  108. {
  109. return ['*'];
  110. }
  111. /**
  112. * 获取详情页面查询的字段.
  113. *
  114. * @return array
  115. */
  116. public function getDetailColumns()
  117. {
  118. return ['*'];
  119. }
  120. /**
  121. * 设置关联关系.
  122. *
  123. * @param mixed $relations
  124. *
  125. * @return $this
  126. */
  127. public function setRelations($relations)
  128. {
  129. $this->relations = (array) $relations;
  130. return $this;
  131. }
  132. /**
  133. * 查询Grid表格数据.
  134. *
  135. * @param Grid\Model $model
  136. *
  137. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|Collection|array
  138. */
  139. public function get(Grid\Model $model)
  140. {
  141. $this->setSort($model);
  142. $this->setPaginate($model);
  143. $query = $this->newQuery();
  144. if ($this->relations) {
  145. $query->with($this->relations);
  146. }
  147. return $model->apply($query, true, $this->getGridColumns());
  148. }
  149. /**
  150. * 设置表格数据排序.
  151. *
  152. * @param Grid\Model $model
  153. *
  154. * @return void
  155. */
  156. protected function setSort(Grid\Model $model)
  157. {
  158. [$column, $type, $cast] = $model->getSort();
  159. if (empty($column) || empty($type)) {
  160. $orders = $model->getSortQueries();
  161. $model->resetOrderBy();
  162. $orders->each(function ($orderBy) use ($model) {
  163. $column = $orderBy['arguments'][0];
  164. $type = in_array($orderBy['method'], $model->getSortDescMethods(), true) ? 'desc' : ($orderBy['arguments'][1] ?? 'asc');
  165. $cast = null;
  166. $this->addOrderBy($model, $column, $type, $cast);
  167. });
  168. return;
  169. }
  170. $model->resetOrderBy();
  171. $this->addOrderBy($model, $column, $type, $cast);
  172. }
  173. /**
  174. * @param Grid\Model $model
  175. * @param string $column
  176. * @param string $type
  177. * @param string $cast
  178. *
  179. * @throws \Exception
  180. */
  181. protected function addOrderBy(Grid\Model $model, $column, $type, $cast)
  182. {
  183. $explodedCols = explode('.', $column);
  184. $isRelation = empty($explodedCols[1]) ? false : method_exists($this->model(), $explodedCols[0]);
  185. if (count($explodedCols) > 1 && $isRelation) {
  186. $this->setRelationSort($model, $column, $type, $cast);
  187. return;
  188. }
  189. $this->setOrderBy(
  190. $model,
  191. str_replace('.', '->', $column),
  192. $type,
  193. $cast);
  194. }
  195. /**
  196. * @param Grid\Model $model
  197. * @param $column
  198. * @param $type
  199. *
  200. * @param $cast
  201. */
  202. protected function setOrderBy(Grid\Model $model, $column, $type, $cast)
  203. {
  204. $isJsonColumn = Str::contains($column, '->');
  205. if ($isJsonColumn) {
  206. $explodedCols = explode('->', $column);
  207. // json字段排序
  208. $col = $this->wrapMySqlColumn(array_shift($explodedCols));
  209. $parts = implode('.', $explodedCols);
  210. $column = "JSON_UNQUOTE(JSON_EXTRACT({$col}, '$.{$parts}'))";
  211. }
  212. if (! empty($cast)) {
  213. $column = $this->wrapMySqlColumn($column);
  214. $model->addQuery(
  215. 'orderByRaw',
  216. ["CAST({$column} AS {$cast}) {$type}"]
  217. );
  218. return;
  219. }
  220. if ($isJsonColumn) {
  221. $model->addQuery('orderByRaw', ["{$column} {$type}"]);
  222. } else {
  223. $model->addQuery('orderBy', [$column, $type]);
  224. }
  225. }
  226. /**
  227. * @param string $column
  228. *
  229. * @return string
  230. */
  231. protected function wrapMySqlColumn($column)
  232. {
  233. if (Str::contains($column, '`')) {
  234. return $column;
  235. }
  236. $columns = explode('.', $column);
  237. foreach ($columns as &$column) {
  238. if (! Str::contains($column, '`')) {
  239. $column = "`{$column}`";
  240. }
  241. }
  242. return implode('.', $columns);
  243. }
  244. /**
  245. * 设置关联数据排序.
  246. *
  247. * @param Grid\Model $model
  248. * @param string $column
  249. * @param string $type
  250. * @param string $cast
  251. *
  252. * @throws \Exception
  253. */
  254. protected function setRelationSort(Grid\Model $model, $column, $type, $cast)
  255. {
  256. [$relationName, $relationColumn] = explode('.', $column, 2);
  257. $relation = $this->model()->$relationName();
  258. $model->addQuery('select', [$this->model()->getTable().'.*']);
  259. $model->addQuery('join', $this->joinParameters($relation));
  260. $this->setOrderBy(
  261. $model,
  262. $relation->getRelated()->getTable().'.'.str_replace('.', '->', $relationColumn),
  263. $type,
  264. $cast
  265. );
  266. }
  267. /**
  268. * 关联模型 join 连接查询.
  269. *
  270. * @param Relation $relation
  271. *
  272. * @throws \Exception
  273. *
  274. * @return array
  275. */
  276. protected function joinParameters(Relation $relation)
  277. {
  278. $relatedTable = $relation->getRelated()->getTable();
  279. if ($relation instanceof BelongsTo) {
  280. $foreignKeyMethod = version_compare(app()->version(), '5.8.0', '<') ? 'getForeignKey' : 'getForeignKeyName';
  281. return [
  282. $relatedTable,
  283. $relation->{$foreignKeyMethod}(),
  284. '=',
  285. $relatedTable.'.'.$relation->getRelated()->getKeyName(),
  286. ];
  287. }
  288. if ($relation instanceof HasOne) {
  289. return [
  290. $relatedTable,
  291. $relation->getQualifiedParentKeyName(),
  292. '=',
  293. $relation->getQualifiedForeignKeyName(),
  294. ];
  295. }
  296. throw new AdminException('Related sortable only support `HasOne` and `BelongsTo` relation.');
  297. }
  298. /**
  299. * 设置分页参数.
  300. *
  301. * @param Grid\Model $model
  302. *
  303. * @return void
  304. */
  305. protected function setPaginate(Grid\Model $model)
  306. {
  307. $paginateMethod = $model->getPaginateMethod();
  308. $paginate = $model->findQueryByMethod($paginateMethod)->first();
  309. $model->rejectQuery(['paginate', 'simplePaginate']);
  310. if (! $model->allowPagination()) {
  311. $model->addQuery('get', [$this->getGridColumns()]);
  312. } else {
  313. $model->addQuery($paginateMethod, $this->resolvePerPage($model, $paginate));
  314. }
  315. }
  316. /**
  317. * 获取分页参数.
  318. *
  319. * @param Grid\Model $model
  320. * @param array|null $paginate
  321. *
  322. * @return array
  323. */
  324. protected function resolvePerPage(Grid\Model $model, $paginate)
  325. {
  326. if ($paginate && is_array($paginate)) {
  327. if ($perPage = request()->input($model->getPerPageName())) {
  328. $paginate['arguments'][0] = (int) $perPage;
  329. }
  330. return $paginate['arguments'];
  331. }
  332. return [
  333. $model->getPerPage(),
  334. $this->getGridColumns(),
  335. $model->getPageName(),
  336. $model->getCurrentPage(),
  337. ];
  338. }
  339. /**
  340. * 查询编辑页面数据.
  341. *
  342. * @param Form $form
  343. *
  344. * @return array|\Illuminate\Contracts\Support\Arrayable
  345. */
  346. public function edit(Form $form)
  347. {
  348. $query = $this->newQuery();
  349. if ($this->isSoftDeletes) {
  350. $query->withTrashed();
  351. }
  352. $this->model = $query
  353. ->with($this->getRelations())
  354. ->findOrFail($form->getKey(), $this->getFormColumns());
  355. return $this->model;
  356. }
  357. /**
  358. * 查询详情页面数据.
  359. *
  360. * @param Show $show
  361. *
  362. * @return array|\Illuminate\Contracts\Support\Arrayable
  363. */
  364. public function detail(Show $show)
  365. {
  366. $query = $this->newQuery();
  367. if ($this->isSoftDeletes) {
  368. $query->withTrashed();
  369. }
  370. $this->model = $query
  371. ->with($this->getRelations())
  372. ->findOrFail($show->getKey(), $this->getDetailColumns());
  373. return $this->model;
  374. }
  375. /**
  376. * 新增记录.
  377. *
  378. * @param Form $form
  379. *
  380. * @return mixed
  381. */
  382. public function store(Form $form)
  383. {
  384. $result = null;
  385. DB::transaction(function () use ($form, &$result) {
  386. $model = $this->model();
  387. $updates = $form->updates();
  388. [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);
  389. if ($relations) {
  390. $updates = Arr::except($updates, array_keys($relationKeyMap));
  391. }
  392. foreach ($updates as $column => $value) {
  393. $model->setAttribute($column, $value);
  394. }
  395. $result = $model->save();
  396. $this->updateRelation($form, $model, $relations, $relationKeyMap);
  397. });
  398. return $this->model()->getKey();
  399. }
  400. /**
  401. * 查询更新前的行数据.
  402. *
  403. * @param Form $form
  404. *
  405. * @return array|\Illuminate\Contracts\Support\Arrayable
  406. */
  407. public function updating(Form $form)
  408. {
  409. return $this->edit($form);
  410. }
  411. /**
  412. * 更新数据.
  413. *
  414. * @param Form $form
  415. *
  416. * @return bool
  417. */
  418. public function update(Form $form)
  419. {
  420. /* @var EloquentModel $builder */
  421. $model = $this->model();
  422. if (! $model->getKey()) {
  423. $model->exists = true;
  424. $model->setAttribute($model->getKeyName(), $form->getKey());
  425. }
  426. $result = null;
  427. DB::transaction(function () use ($form, $model, &$result) {
  428. $updates = $form->updates();
  429. [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);
  430. if ($relations) {
  431. $updates = Arr::except($updates, array_keys($relationKeyMap));
  432. }
  433. foreach ($updates as $column => $value) {
  434. /* @var EloquentModel $model */
  435. $model->setAttribute($column, $value);
  436. }
  437. $result = $model->update();
  438. $this->updateRelation($form, $model, $relations, $relationKeyMap);
  439. });
  440. return $result;
  441. }
  442. /**
  443. * 数据行排序上移一个单位.
  444. *
  445. * @return bool
  446. */
  447. public function moveOrderUp()
  448. {
  449. $model = $this->model();
  450. if (! $model instanceof Sortable) {
  451. throw new RuntimeException(
  452. sprintf(
  453. 'The model "%s" must be a type of %s.',
  454. get_class($model),
  455. Sortable::class
  456. )
  457. );
  458. }
  459. return $model->moveOrderUp() ? true : false;
  460. }
  461. /**
  462. * 数据行排序下移一个单位.
  463. *
  464. * @return bool
  465. */
  466. public function moveOrderDown()
  467. {
  468. $model = $this->model();
  469. if (! $model instanceof Sortable) {
  470. throw new RuntimeException(
  471. sprintf(
  472. 'The model "%s" must be a type of %s.',
  473. get_class($model),
  474. Sortable::class
  475. )
  476. );
  477. }
  478. return $model->moveOrderDown() ? true : false;
  479. }
  480. /**
  481. * 删除数据.
  482. *
  483. * @param Form $form
  484. * @param array $originalData
  485. *
  486. * @return bool
  487. */
  488. public function delete(Form $form, array $originalData)
  489. {
  490. $models = $this->collection->keyBy($this->getKeyName());
  491. collect(explode(',', $form->getKey()))->filter()->each(function ($id) use ($form, $models) {
  492. $model = $models->get($id);
  493. if (! $model) {
  494. return;
  495. }
  496. $data = $model->toArray();
  497. if ($this->isSoftDeletes && $model->trashed()) {
  498. $form->deleteFiles($data, true);
  499. $model->forceDelete();
  500. return;
  501. } elseif (! $this->isSoftDeletes) {
  502. $form->deleteFiles($data);
  503. }
  504. $model->delete();
  505. });
  506. return true;
  507. }
  508. /**
  509. * 查询删除前的行数据.
  510. *
  511. * @param Form $form
  512. *
  513. * @return array
  514. */
  515. public function deleting(Form $form)
  516. {
  517. $query = $this->newQuery();
  518. if ($this->isSoftDeletes) {
  519. $query->withTrashed();
  520. }
  521. $id = $form->getKey();
  522. $this->collection = $query
  523. ->with($this->getRelations())
  524. ->findOrFail(
  525. collect(explode(',', $id))->filter()->toArray(),
  526. $this->getFormColumns()
  527. );
  528. return $this->collection->toArray();
  529. }
  530. /**
  531. * 获取父级ID字段名称.
  532. *
  533. * @return string
  534. */
  535. public function getParentColumn()
  536. {
  537. $model = $this->model();
  538. if (method_exists($model, 'getParentColumn')) {
  539. return $model->getParentColumn();
  540. }
  541. }
  542. /**
  543. * 获取标题字段名称.
  544. *
  545. * @return string
  546. */
  547. public function getTitleColumn()
  548. {
  549. $model = $this->model();
  550. if (method_exists($model, 'getTitleColumn')) {
  551. return $model->getTitleColumn();
  552. }
  553. }
  554. /**
  555. * 获取排序字段名称.
  556. *
  557. * @return string
  558. */
  559. public function getOrderColumn()
  560. {
  561. $model = $this->model();
  562. if (method_exists($model, 'getOrderColumn')) {
  563. return $model->getOrderColumn();
  564. }
  565. }
  566. /**
  567. * 保存层级数据排序.
  568. *
  569. * @param array $tree
  570. * @param int $parentId
  571. */
  572. public function saveOrder($tree = [], $parentId = 0)
  573. {
  574. $this->model()->saveOrder($tree, $parentId);
  575. }
  576. /**
  577. * 设置数据查询回调.
  578. *
  579. * @param \Closure|null $query
  580. *
  581. * @return $this
  582. */
  583. public function withQuery($queryCallback)
  584. {
  585. $this->model()->withQuery($queryCallback);
  586. return $this;
  587. }
  588. /**
  589. * 获取层级数据.
  590. *
  591. * @return array
  592. */
  593. public function toTree()
  594. {
  595. if ($this->relations) {
  596. $this->withQuery(function ($model) {
  597. return $model->with($this->relations);
  598. });
  599. }
  600. return $this->model()->toTree();
  601. }
  602. /**
  603. * @return Builder
  604. */
  605. protected function newQuery()
  606. {
  607. if ($this->queryBuilder) {
  608. return clone $this->queryBuilder;
  609. }
  610. return $this->model()->newQuery();
  611. }
  612. /**
  613. * 获取model对象.
  614. *
  615. * @return EloquentModel
  616. */
  617. public function model()
  618. {
  619. return $this->model ?: ($this->model = $this->createModel());
  620. }
  621. /**
  622. * @param array $data
  623. *
  624. * @return EloquentModel
  625. */
  626. public function createModel(array $data = [])
  627. {
  628. $model = new $this->eloquentClass();
  629. if ($data) {
  630. $model->setRawAttributes($data);
  631. }
  632. return $model;
  633. }
  634. /**
  635. * @param array $relations
  636. *
  637. * @return $this
  638. */
  639. public static function with($relations = [])
  640. {
  641. return (new static())->setRelations($relations);
  642. }
  643. /**
  644. * 获取模型的所有关联关系.
  645. *
  646. * @return array
  647. */
  648. public function getRelations()
  649. {
  650. return $this->relations;
  651. }
  652. /**
  653. * 获取模型关联关系的表单数据.
  654. *
  655. * @param EloquentModel $model
  656. * @param array $inputs
  657. *
  658. * @return array
  659. */
  660. protected function getRelationInputs($model, $inputs = [])
  661. {
  662. $map = [];
  663. $relations = [];
  664. foreach ($inputs as $column => $value) {
  665. $relationColumn = null;
  666. if (method_exists($model, $column)) {
  667. $relationColumn = $column;
  668. } elseif (method_exists($model, $camelColumn = Str::camel($column))) {
  669. $relationColumn = $camelColumn;
  670. }
  671. if (! $relationColumn) {
  672. continue;
  673. }
  674. $relation = call_user_func([$model, $relationColumn]);
  675. if ($relation instanceof Relations\Relation) {
  676. $relations[$column] = $value;
  677. $map[$column] = $relationColumn;
  678. }
  679. }
  680. return [&$relations, $map];
  681. }
  682. /**
  683. * 更新关联关系数据.
  684. *
  685. * @param Form $form
  686. * @param EloquentModel $model
  687. * @param array $relationsData
  688. * @param array $relationKeyMap
  689. *
  690. * @throws \Exception
  691. */
  692. protected function updateRelation(Form $form, EloquentModel $model, array $relationsData, array $relationKeyMap)
  693. {
  694. foreach ($relationsData as $name => $values) {
  695. $relationName = $relationKeyMap[$name] ?? $name;
  696. if (! method_exists($model, $relationName)) {
  697. continue;
  698. }
  699. $relation = $model->$relationName();
  700. $oneToOneRelation = $relation instanceof Relations\HasOne
  701. || $relation instanceof Relations\MorphOne
  702. || $relation instanceof Relations\BelongsTo;
  703. $prepared = $oneToOneRelation ? $form->prepareUpdate([$name => $values]) : [$name => $values];
  704. if (empty($prepared)) {
  705. continue;
  706. }
  707. switch (true) {
  708. case $relation instanceof Relations\BelongsToMany:
  709. case $relation instanceof Relations\MorphToMany:
  710. if (isset($prepared[$name])) {
  711. $relation->sync($prepared[$name]);
  712. }
  713. break;
  714. case $relation instanceof Relations\HasOne:
  715. $related = $model->$relationName;
  716. // if related is empty
  717. if (is_null($related)) {
  718. $related = $relation->getRelated();
  719. $qualifiedParentKeyName = $relation->getQualifiedParentKeyName();
  720. $localKey = Arr::last(explode('.', $qualifiedParentKeyName));
  721. $related->{$relation->getForeignKeyName()} = $model->{$localKey};
  722. }
  723. foreach ($prepared[$name] as $column => $value) {
  724. $related->setAttribute($column, $value);
  725. }
  726. $related->save();
  727. break;
  728. case $relation instanceof Relations\BelongsTo:
  729. case $relation instanceof Relations\MorphTo:
  730. $parent = $model->$relationName;
  731. // if related is empty
  732. if (is_null($parent)) {
  733. $parent = $relation->getRelated();
  734. }
  735. foreach ($prepared[$name] as $column => $value) {
  736. $parent->setAttribute($column, $value);
  737. }
  738. $parent->save();
  739. // When in creating, associate two models
  740. $foreignKeyMethod = version_compare(app()->version(), '5.8.0', '<') ? 'getForeignKey' : 'getForeignKeyName';
  741. if (! $model->{$relation->{$foreignKeyMethod}()}) {
  742. $model->{$relation->{$foreignKeyMethod}()} = $parent->getKey();
  743. $model->save();
  744. }
  745. break;
  746. case $relation instanceof Relations\MorphOne:
  747. $related = $model->$relationName;
  748. if (is_null($related)) {
  749. $related = $relation->make();
  750. }
  751. foreach ($prepared[$name] as $column => $value) {
  752. $related->setAttribute($column, $value);
  753. }
  754. $related->save();
  755. break;
  756. case $relation instanceof Relations\HasMany:
  757. case $relation instanceof Relations\MorphMany:
  758. foreach ($prepared[$name] as $related) {
  759. /** @var Relations\Relation $relation */
  760. $relation = $model->$relationName();
  761. $keyName = $relation->getRelated()->getKeyName();
  762. $instance = $relation->findOrNew(Arr::get($related, $keyName));
  763. if (Arr::get($related, Form::REMOVE_FLAG_NAME) == 1) {
  764. $instance->delete();
  765. continue;
  766. }
  767. Arr::forget($related, Form::REMOVE_FLAG_NAME);
  768. $key = Arr::get($related, $relation->getModel()->getKeyName());
  769. if ($key === null || $key === '') {
  770. Arr::forget($related, $relation->getModel()->getKeyName());
  771. }
  772. $instance->fill($related);
  773. $instance->save();
  774. }
  775. break;
  776. }
  777. }
  778. }
  779. }