EloquentRepository.php 20 KB

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