json(4001, '记录不存在'); } if ($this->request->isPost()) { $item = input('post.'); $validate = $this->validateByApi($item, [ 'pid|父级分类' => 'require|number', 'name|标题' => 'require|max:100', ]); if ($validate !== true) { return $validate; } Db::startTrans(); try { $info->save($item); Db::commit(); return $this->json(); } catch (ValidateException $e) { Db::rollback(); return $this->json(4001, $e->getError()); } } $disabled = CategoryModel::getAllChildrenIds($id); $disabled[] = $id; $this->data['jsonList'] = $this->categoryJson([$info['pid']], $disabled); $this->data['item'] = $info; return $this->view(); } /** * 添加 * * @return Json|View * @throws Exception */ public function add() { if ($this->request->isPost()) { $item = input('post.'); $validate = $this->validateByApi($item, [ 'pid|父级分类' => 'require|number', 'name|标题' => 'require|max:100', ]); if ($validate !== true) { return $validate; } try { CategoryModel::create($item); return $this->json(); } catch (ValidateException $e) { return $this->json(4001, $e->getError()); } } $this->data['jsonList'] = $this->categoryJson(); return $this->view(); } /** * 删除 * @return Json */ public function del() { if (!$this->request->isPost()) { return $this->json(4000, '非法请求'); } $ids = $this->request->param('ids/a', []); if(!empty(CategoryModel::findOne([["pid","in",$ids]]))){ return $this->json(4001,"该栏目还有下级,不能删除"); } $business = BusinessRepository::getInstance()->findOneByWhere([["type","in",$ids]]); if(!empty($business)){ return $this->json(4001,"该栏目还有商家存在,不能删除"); } CategoryModel::destroy($ids); return $this->json(); } /** * 列表 * * @return Json|View * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ public function index() { if ($this->request->isPost()) { $menus = CategoryModel::getList(); $res = [ 'code' => 0, 'msg' => 'success', 'count' => $menus->count(), 'data' => $menus->toArray(), ]; return json($res); } return $this->view(); } /** * @param array $selected * @param array $disabled * @return false|string * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ private function categoryJson(array $selected = [], array $disabled = []) { $categoryList[] = ['name' => '顶级分类', 'id' => 0, 'disabled' => false, 'selected' => in_array(0, $selected)]; $list = CategoryModel::getListByPid(); $list = $list->toArray(); foreach ($list as $k => $m) { $list[$k]['selected'] = in_array($m['id'], $selected); $list[$k]['disabled'] = in_array($m['id'], $disabled); } $list = CmsRepository::getInstance()->buildMenuChild(0, $list); $categoryList = array_merge($categoryList, CmsRepository::getInstance()->handleSelectedList($list)); return json_encode($categoryList, JSON_UNESCAPED_UNICODE); } }