Operation.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. /**
  5. * 大屏操作
  6. */
  7. class Operation extends Backend
  8. {
  9. /**
  10. * Operation模型对象
  11. * @var object
  12. * @phpstan-var \app\admin\model\Operation
  13. */
  14. protected object $model;
  15. protected array|string $preExcludeFields = ['id', 'update_time', 'create_time'];
  16. protected string|array $quickSearchField = ['id'];
  17. public function initialize(): void
  18. {
  19. parent::initialize();
  20. $this->model = new \app\admin\model\Operation;
  21. }
  22. /**
  23. * 若需重写查看、编辑、删除等方法,请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
  24. */
  25. /**
  26. * 编辑
  27. * @throws Throwable
  28. */
  29. public function edit(): void
  30. {
  31. $pk = $this->model->getPk();
  32. $id = $this->request->param($pk);
  33. $row = $this->model->find($id);
  34. if (!$row) {
  35. $this->error(__('Record not found'));
  36. }
  37. $dataLimitAdminIds = $this->getDataLimitAdminIds();
  38. if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
  39. $this->error(__('You have no permission'));
  40. }
  41. if ($this->request->isPost()) {
  42. $data = $this->request->post();
  43. if (!$data) {
  44. $this->error(__('Parameter %s can not be empty', ['']));
  45. }
  46. if( $data['switch'] == 0 && !isset($data['types'])){
  47. $this->error('请确保至少有一种协议正在使用中!');
  48. }
  49. $data = $this->excludeFields($data);
  50. $result = false;
  51. $this->model->startTrans();
  52. try {
  53. // 模型验证
  54. if ($this->modelValidate) {
  55. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  56. if (class_exists($validate)) {
  57. $validate = new $validate;
  58. if ($this->modelSceneValidate) $validate->scene('edit');
  59. $data[$pk] = $row[$pk];
  60. $validate->check($data);
  61. }
  62. }
  63. if( $data['switch'] == 1 && !isset($data['types'])){
  64. $this->model->where('switch',1)->update(['switch' => 0]);
  65. }
  66. $result = $row->save($data);
  67. $this->model->commit();
  68. } catch (Throwable $e) {
  69. $this->model->rollback();
  70. $this->error($e->getMessage());
  71. }
  72. if ($result !== false) {
  73. $this->success(__('Update successful'));
  74. } else {
  75. $this->error(__('No rows updated'));
  76. }
  77. }
  78. $this->success('', [
  79. 'row' => $row
  80. ]);
  81. }
  82. }