Curd.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. namespace app\admin\traits;
  3. use app\admin\service\annotation\NodeAnnotation;
  4. use app\admin\service\tool\CommonTool;
  5. use app\Request;
  6. use think\db\exception\PDOException;
  7. use think\facade\Db;
  8. use think\response\Json;
  9. /**
  10. * 后台CURD复用
  11. * Trait Curd
  12. * @package app\admin\traits
  13. */
  14. trait Curd
  15. {
  16. #[NodeAnnotation(title: '列表', auth: true)]
  17. public function index(Request $request): Json|string
  18. {
  19. if ($request->isAjax()) {
  20. if (input('selectFields')) {
  21. return $this->selectList();
  22. }
  23. list($page, $limit, $where) = $this->buildTableParams();
  24. $count = self::$model::where($where)->count();
  25. $list = self::$model::where($where)->page($page, $limit)->order($this->sort)->select()->toArray();
  26. $data = [
  27. 'code' => 0,
  28. 'msg' => '',
  29. 'count' => $count,
  30. 'data' => $list,
  31. ];
  32. return json($data);
  33. }
  34. return $this->fetch();
  35. }
  36. #[NodeAnnotation(title: '添加', auth: true)]
  37. public function add(Request $request): string
  38. {
  39. if ($request->isPost()) {
  40. $post = $request->post();
  41. $rule = [];
  42. $this->validate($post, $rule);
  43. try {
  44. Db::transaction(function() use ($post, &$save) {
  45. $save = self::$model::create($post);
  46. });
  47. }catch (\Exception $e) {
  48. $this->error('新增失败:' . $e->getMessage());
  49. }
  50. $save ? $this->success('新增成功') : $this->error('新增失败');
  51. }
  52. return $this->fetch();
  53. }
  54. #[NodeAnnotation(title: '编辑', auth: true)]
  55. public function edit(Request $request, $id = 0): string
  56. {
  57. $row = self::$model::find($id);
  58. empty($row) && $this->error('数据不存在');
  59. if ($request->isPost()) {
  60. $post = $request->post();
  61. $rule = [];
  62. $this->validate($post, $rule);
  63. try {
  64. Db::transaction(function() use ($post, $row, &$save) {
  65. $save = $row->save($post);
  66. });
  67. }catch (\Exception $e) {
  68. $this->error('保存失败');
  69. }
  70. $save ? $this->success('保存成功') : $this->error('保存失败');
  71. }
  72. $this->assign('row', $row);
  73. return $this->fetch();
  74. }
  75. #[NodeAnnotation(title: '删除', auth: true)]
  76. public function delete(Request $request): void
  77. {
  78. // 如果不是id作为主键 请在对应的控制器中覆盖重写
  79. $id = $request->param('id', []);
  80. $this->checkPostRequest();
  81. $row = self::$model::whereIn('id', $id)->select();
  82. $row->isEmpty() && $this->error('数据不存在');
  83. try {
  84. $save = $row->delete();
  85. }catch (\Exception $e) {
  86. $this->error('删除失败');
  87. }
  88. $save ? $this->success('删除成功') : $this->error('删除失败');
  89. }
  90. #[NodeAnnotation(title: '导出', auth: true)]
  91. public function export()
  92. {
  93. if (env('EASYADMIN.IS_DEMO', false)) {
  94. $this->error('演示环境下不允许操作');
  95. }
  96. list($page, $limit, $where) = $this->buildTableParams();
  97. $tableName = (new self::$model)->getName();
  98. $tableName = CommonTool::humpToLine(lcfirst($tableName));
  99. $prefix = config('database.connections.mysql.prefix');
  100. $dbList = Db::query("show full columns from {$prefix}{$tableName}");
  101. $header = [];
  102. foreach ($dbList as $vo) {
  103. $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
  104. if (!in_array($vo['Field'], $this->noExportFields)) {
  105. $header[] = [$comment, $vo['Field']];
  106. }
  107. }
  108. $list = self::$model::where($where)
  109. ->limit(100000)
  110. ->order($this->sort)
  111. ->select()
  112. ->toArray();
  113. try {
  114. exportExcel($header, $list);
  115. }catch (\Throwable $exception) {
  116. $this->error('导出失败: ' . $exception->getMessage() . PHP_EOL . $exception->getFile() . PHP_EOL . $exception->getLine());
  117. }
  118. }
  119. #[NodeAnnotation(title: '属性修改', auth: true)]
  120. public function modify(Request $request): void
  121. {
  122. $this->checkPostRequest();
  123. $post = $request->post();
  124. $rule = [
  125. 'id|ID' => 'require',
  126. 'field|字段' => 'require',
  127. 'value|值' => 'require',
  128. ];
  129. $this->validate($post, $rule);
  130. $row = self::$model::find($post['id']);
  131. if (!$row) {
  132. $this->error('数据不存在');
  133. }
  134. if (!in_array($post['field'], $this->allowModifyFields)) {
  135. $this->error('该字段不允许修改:' . $post['field']);
  136. }
  137. try {
  138. Db::transaction(function() use ($post, $row) {
  139. $row->save([
  140. $post['field'] => $post['value'],
  141. ]);
  142. });
  143. }catch (\Exception $e) {
  144. $this->error($e->getMessage());
  145. }
  146. $this->success('保存成功');
  147. }
  148. #[NodeAnnotation(title: '回收站', auth: true)]
  149. public function recycle(Request $request): Json|string
  150. {
  151. if (!$request->isAjax()) {
  152. return $this->fetch();
  153. }
  154. $id = $request->param('id', []);
  155. $type = $request->param('type', '');
  156. $deleteTimeField = (new self::$model)->getOption('deleteTime'); // 获取软删除字段
  157. $defaultErrorMsg = 'Model 中未设置软删除 deleteTime 对应字段 或 数据表中不存在该字段';
  158. if (!$deleteTimeField) $this->success($defaultErrorMsg);
  159. switch ($type) {
  160. case 'restore':
  161. self::$model::withTrashed()->whereIn('id', $id)->strict(false)->update([$deleteTimeField => null, 'update_time' => time()]);
  162. $this->success('success');
  163. break;
  164. case 'delete':
  165. self::$model::destroy($id, true);
  166. $this->success('success');
  167. break;
  168. default:
  169. list($page, $limit, $where) = $this->buildTableParams();
  170. try {
  171. $count = self::$model::withTrashed()->where($where)->whereNotNull($deleteTimeField)->count();
  172. $list = self::$model::withTrashed()->where($where)->page($page, $limit)->order($this->sort)->whereNotNull($deleteTimeField)->select()->toArray();
  173. $data = [
  174. 'code' => 0,
  175. 'msg' => '',
  176. 'count' => $count,
  177. 'data' => $list,
  178. ];
  179. } catch (\Throwable $e) {
  180. $error = $e->getMessage();
  181. if ($e instanceof PDOException) $error .= '<br>' . $defaultErrorMsg;
  182. $data = [
  183. 'code' => -1,
  184. 'msg' => $error,
  185. 'count' => 0,
  186. 'data' => [],
  187. ];
  188. }
  189. return json($data);
  190. }
  191. }
  192. }