-a reload 生效): * 列表 index * 新增 add * 编辑 update * 删除 delete */ class {%className%} extends BackendBase { /** * 免登录动作 * @var array */ protected $noNeedLogin = []; /** * 免鉴权动作 * @var array */ protected $noNeedVerify = []; protected function initialize() { parent::initialize(); } /** * 列表(AJAX 返回 layui 表格数据) */ public function index() { if ($this->request->isAjax()) { $page = (int) $this->request->param('page', 1); $limit = (int) $this->request->param('limit', 15); $query = {%modelAlias%}::where('{%pk%}', '>', 0);{%search%} $data = $query->order('{%pk%}', 'desc')->paginate([ 'page' => $page, 'list_rows' => $limit, ]); // 必须回传 count,否则 layui 表格分页失效 return json(['code' => 0, 'msg' => '', 'count' => $data->total(), 'data' => $data->items()]); } return $this->view->fetch('{%viewDir%}/index'); } /** * 新增 */ public function add() { return $this->saveRow(0); } /** * 更新 */ public function update() { return $this->saveRow((int) Request::post('id', 0)); } /** * 删除(软删除字段存在时为软删除) */ public function delete() { $id = (int) Request::post('id', 0); if ($id <= 0) { return json(['code' => 0, 'msg' => '参数错误']); } $row = {%modelAlias%}::find($id); if (!$row) { return json(['code' => 0, 'msg' => '记录不存在']); } $row->delete(); return json(['code' => 1, 'msg' => '已删除']); } /** * 写入(新增 / 更新共用) */ protected function saveRow(int $id) { $data = Request::post(); $validate = new Validate([{%rules%}]); if (!$validate->check($data)) { return json(['code' => 0, 'msg' => $validate->getError()]); } // 字段白名单,避免把非表字段写进 SQL $allow = [{%allow%}]; try { if ($id > 0) { $row = {%modelAlias%}::find($id); if (!$row) { return json(['code' => 0, 'msg' => '记录不存在']); } $row->allowField($allow)->save($data); } else { {%modelAlias%}::create($data, $allow); } } catch (\Throwable $e) { return json(['code' => 0, 'msg' => '保存失败:' . $e->getMessage()]); } return json(['code' => 1, 'msg' => '保存成功']); } }