Protocol.php 2.9 KB

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