| // +------------------------------------------------+ namespace app\common\service; use app\common\model\Category as CategoryModel; use app\common\validate\Category as CategoryValidate; use think\Db; use tools\Tree; class Category extends _Init { /** * 树形展示 * @return [type] [description] */ public static function tree() { $map = [ 'status' => 1, ]; $field = [ 'id', 'pid', 'title' => 'name', 'true as spread', ]; $list = Db::name('Category')->field($field)->where($map)->order('sort asc')->select(); $menu = Tree::list2tree($list); return json_encode($menu); } /** * 分类列表 * @param integer $id 要排查的分类id * @return [type] 返回分类列表 */ public static function treeList($id = 0) { $map = []; if ($id) { $map['id'] = ['neq', $id]; } $menus = Db::name('Category')->where($map)->order('sort asc')->select(); $menus = Tree::toFormatTree($menus); $menus = array_merge([0 => ['id' => 0, 'title_show' => '顶级分类']], $menus); return $menus; } /** * 添加分类 * @param [type] $data 分类数据 */ public static function add($data) { $validate = new CategoryValidate(); if (!$validate->check($data)) { return $validate->getError(); } if (CategoryModel::create($data)) { Logs::write('新增分类', $data); return true; } else { return '新曾分类失败'; } } /** * 编辑分类 * @param [type] $data 编辑分类的数据 */ public static function edit($data) { $validate = new CategoryValidate(); if (!$validate->check($data)) { return $validate->getError(); } if (CategoryModel::update($data)) { Logs::write('编辑分类', $data); return true; } else { return '新增分类失败'; } } /** * 删除分类 * @param [type] $id 分类id * @return [type] 返回删除的结果 true 和 错误信息 */ public static function del($id) { if (CategoryModel::where('pid', 'in', $id)->find()) { return $this->error('该分类有下级分类,不允许直接删除'); } $info = CategoryModel::get($id); if (!$info) { return '数据不存在'; } elseif ($info->save(['status' => -1])) { return true; } else { return '删除分类失败'; } } /** * 设置分类状态 * @param [type] $id 分类id * @param [type] $status 状态信息 true false * @param [type] $type 设置的字段 */ public static function status($id, $status, $type) { $info = CategoryModel::get($id); if (!$info) { return $this->error('数据不存在'); } elseif ($info->save([$type => $status])) { Logs::write('修改状态', [$type => $status]); return true; } else { return '设置状态失败'; } } }