EloquentRepository.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. <?php
  2. namespace UCore\DcatAdmin\Repository;
  3. use Dcat\Admin\Form;
  4. use Illuminate\Database\Eloquent\Model as EloquentModel;
  5. use Illuminate\Support\Arr;
  6. use Illuminate\Support\Facades\DB;
  7. class EloquentRepository extends \Dcat\Admin\Repositories\EloquentRepository
  8. {
  9. public function getEloquentClass()
  10. {
  11. return $this->eloquentClass;
  12. }
  13. /**
  14. * 更新后
  15. *
  16. * @var array
  17. */
  18. public $update_after;
  19. /**
  20. * 更新前
  21. *
  22. * @var array
  23. */
  24. public $update_before;
  25. /**
  26. * 新增, 生成数据
  27. *
  28. * @var array
  29. */
  30. public $add_after;
  31. /**
  32. * 新增 传入数据
  33. * @var array
  34. */
  35. public $add_before;
  36. /**
  37. * 新增记录.
  38. *
  39. * @param Form $form
  40. * @return mixed
  41. */
  42. public function store(Form $form)
  43. {
  44. $result = null;
  45. DB::transaction(function () use ($form, &$result) {
  46. $model = $this->model();
  47. $updates = $form->updates();
  48. [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);
  49. if ($relations) {
  50. $updates = Arr::except($updates, array_keys($relationKeyMap));
  51. }
  52. $this->add_before = $updates;
  53. foreach ($updates as $column => $value) {
  54. $model->setAttribute($column, $value);
  55. }
  56. $result = $model->save();
  57. $this->add_after = $model->toArray();
  58. $this->updateRelation($form, $model, $relations, $relationKeyMap);
  59. });
  60. return $this->model()->getKey();
  61. }
  62. /**
  63. * 更新数据.
  64. *
  65. * @param Form $form
  66. * @return bool
  67. */
  68. public function update(Form $form)
  69. {
  70. /* @var EloquentModel $builder */
  71. $model = $this->model();
  72. if (!$model->getKey()) {
  73. $model->exists = true;
  74. $model->setAttribute($model->getKeyName(), $form->getKey());
  75. }
  76. $result = null;
  77. DB::transaction(function () use ($form, $model, &$result) {
  78. $updates = $form->updates();
  79. [ $relations, $relationKeyMap ] = $this->getRelationInputs($model, $updates);
  80. if ($relations) {
  81. $updates = Arr::except($updates, array_keys($relationKeyMap));
  82. }
  83. foreach ($updates as $column => $value) {
  84. $this->update_before[$column] = $model->getAttribute($column);
  85. /* @var EloquentModel $model */
  86. $model->setAttribute($column, $value);
  87. $this->update_after[$column] = $model->getAttribute($column);
  88. }
  89. $result = $model->update();
  90. $this->updateRelation($form, $model, $relations, $relationKeyMap);
  91. });
  92. return $result;
  93. }
  94. }