Backend.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. namespace app\admin\library\traits;
  3. use Exception;
  4. use think\facade\Config;
  5. use think\facade\Db;
  6. use think\db\exception\PDOException;
  7. use think\exception\ValidateException;
  8. /**
  9. * 后台控制器trait类
  10. * 已导入到 @var \app\common\controller\Backend 中
  11. * 若需修改此类方法:请复制方法至对应控制器后进行重写
  12. */
  13. trait Backend
  14. {
  15. /**
  16. * 排除入库字段
  17. * @param $params
  18. * @return mixed
  19. */
  20. protected function excludeFields($params)
  21. {
  22. if (!is_array($this->preExcludeFields)) {
  23. $this->preExcludeFields = explode(',', (string)$this->preExcludeFields);
  24. }
  25. foreach ($this->preExcludeFields as $field) {
  26. if (array_key_exists($field, $params)) {
  27. unset($params[$field]);
  28. }
  29. }
  30. return $params;
  31. }
  32. /**
  33. * 查看
  34. */
  35. public function index()
  36. {
  37. $this->request->filter(['strip_tags', 'trim']);
  38. if ($this->request->param('select')) {
  39. $this->select();
  40. }
  41. list($where, $alias, $limit, $order) = $this->queryBuilder();
  42. $res = $this->model
  43. ->field($this->indexField)
  44. ->withJoin($this->withJoinTable, $this->withJoinType)
  45. ->alias($alias)
  46. ->where($where)
  47. ->order($order)
  48. ->paginate($limit);
  49. $this->success('', [
  50. 'list' => $res->items(),
  51. 'total' => $res->total(),
  52. 'remark' => get_route_remark(),
  53. ]);
  54. }
  55. /**
  56. * 添加
  57. */
  58. public function add()
  59. {
  60. if ($this->request->isPost()) {
  61. $data = $this->request->post();
  62. if (!$data) {
  63. $this->error(__('Parameter %s can not be empty', ['']));
  64. }
  65. $data = $this->excludeFields($data);
  66. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  67. $data[$this->dataLimitField] = $this->auth->id;
  68. }
  69. $result = false;
  70. Db::startTrans();
  71. try {
  72. // 模型验证
  73. if ($this->modelValidate) {
  74. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  75. if (class_exists($validate)) {
  76. $validate = new $validate;
  77. if ($this->modelSceneValidate) $validate->scene('add');
  78. $validate->check($data);
  79. }
  80. }
  81. $result = $this->model->save($data);
  82. Db::commit();
  83. } catch (ValidateException|PDOException|Exception $e) {
  84. Db::rollback();
  85. $this->error($e->getMessage());
  86. }
  87. if ($result !== false) {
  88. $this->success(__('Added successfully'));
  89. } else {
  90. $this->error(__('No rows were added'));
  91. }
  92. }
  93. $this->error(__('Parameter error'));
  94. }
  95. /**
  96. * 编辑
  97. */
  98. public function edit()
  99. {
  100. $id = $this->request->param($this->model->getPk());
  101. $row = $this->model->find($id);
  102. if (!$row) {
  103. $this->error(__('Record not found'));
  104. }
  105. $dataLimitAdminIds = $this->getDataLimitAdminIds();
  106. if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
  107. $this->error(__('You have no permission'));
  108. }
  109. if ($this->request->isPost()) {
  110. $data = $this->request->post();
  111. if (!$data) {
  112. $this->error(__('Parameter %s can not be empty', ['']));
  113. }
  114. $data = $this->excludeFields($data);
  115. $result = false;
  116. Db::startTrans();
  117. try {
  118. // 模型验证
  119. if ($this->modelValidate) {
  120. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  121. if (class_exists($validate)) {
  122. $validate = new $validate;
  123. if ($this->modelSceneValidate) $validate->scene('edit');
  124. $validate->check($data);
  125. }
  126. }
  127. $result = $row->save($data);
  128. Db::commit();
  129. } catch (ValidateException|PDOException|Exception $e) {
  130. Db::rollback();
  131. $this->error($e->getMessage());
  132. }
  133. if ($result !== false) {
  134. $this->success(__('Update successful'));
  135. } else {
  136. $this->error(__('No rows updated'));
  137. }
  138. }
  139. $this->success('', [
  140. 'row' => $row
  141. ]);
  142. }
  143. /**
  144. * 删除
  145. * @param array $ids
  146. */
  147. public function del(array $ids = [])
  148. {
  149. if (!$this->request->isDelete() || !$ids) {
  150. $this->error(__('Parameter error'));
  151. }
  152. $dataLimitAdminIds = $this->getDataLimitAdminIds();
  153. if ($dataLimitAdminIds) {
  154. $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
  155. }
  156. $pk = $this->model->getPk();
  157. $data = $this->model->where($pk, 'in', $ids)->select();
  158. $count = 0;
  159. Db::startTrans();
  160. try {
  161. foreach ($data as $v) {
  162. $count += $v->delete();
  163. }
  164. Db::commit();
  165. } catch (PDOException|Exception $e) {
  166. Db::rollback();
  167. $this->error($e->getMessage());
  168. }
  169. if ($count) {
  170. $this->success(__('Deleted successfully'));
  171. } else {
  172. $this->error(__('No rows were deleted'));
  173. }
  174. }
  175. /**
  176. * 排序
  177. * @param int $id 排序主键值
  178. * @param int $targetId 排序位置主键值
  179. */
  180. public function sortable(int $id, int $targetId)
  181. {
  182. $dataLimitAdminIds = $this->getDataLimitAdminIds();
  183. if ($dataLimitAdminIds) {
  184. $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
  185. }
  186. $row = $this->model->find($id);
  187. $target = $this->model->find($targetId);
  188. if (!$row || !$target) {
  189. $this->error(__('Record not found'));
  190. }
  191. if ($row[$this->weighField] == $target[$this->weighField]) {
  192. $autoSortEqWeight = is_null($this->autoSortEqWeight) ? Config::get('buildadmin.auto_sort_eq_weight') : $this->autoSortEqWeight;
  193. if (!$autoSortEqWeight) {
  194. $this->error(__('Invalid collation because the weights of the two targets are equal'));
  195. }
  196. // 自动重新整理排序
  197. $all = $this->model->select();
  198. foreach ($all as $item) {
  199. $item[$this->weighField] = $item[$this->model->getPk()];
  200. $item->save();
  201. }
  202. unset($all);
  203. // 重新获取
  204. $row = $this->model->find($id);
  205. $target = $this->model->find($targetId);
  206. }
  207. $ebak = $target[$this->weighField];
  208. $target[$this->weighField] = $row[$this->weighField];
  209. $row[$this->weighField] = $ebak;
  210. $row->save();
  211. $target->save();
  212. $this->success();
  213. }
  214. /**
  215. * 加载为select(远程下拉选择框)数据,默认还是走$this->index()方法
  216. * 必要时请在对应控制器类中重写
  217. */
  218. public function select()
  219. {
  220. }
  221. }