// +---------------------------------------------------------------------- declare (strict_types=1); namespace app\services\system\attachment; use app\model\system\attachment\SystemAttachmentCategory; use qiniu\basic\BaseServices; use qiniu\exceptions\AdminException; use think\db\exception\DataNotFoundException; use think\db\exception\DbException; use think\db\exception\ModelNotFoundException; use think\facade\Route as Url; /** * * Class SystemAttachmentCategoryServices * @package app\services\attachment * @mixin SystemAttachmentCategory */ class SystemAttachmentCategoryServices extends BaseServices { /** * SystemAttachmentCategoryServices constructor. * @param SystemAttachmentCategory $model */ public function __construct(SystemAttachmentCategory $model) { $this->model = $model; } /** * 获取分类列表 * @param array $where * @return array */ public function getAll(array $where) { $list = $this->getList($where); $list = get_tree_children($list); return compact('list'); } /** * 格式化列表 * @param $menusList * @param int $pid * @param array $navList * @return array */ public function tidyMenuTier($menusList, $pid = 0, $navList = []) { foreach ($menusList as $k => $menu) { $menu['title'] = $menu['name']; if ($menu['pid'] == $pid) { unset($menusList[$k]); $menu['children'] = $this->tidyMenuTier($menusList, $menu['id']); if ($menu['children']) $menu['expand'] = true; $navList[] = $menu; } } return $navList; } /** * 获取分类列表(添加修改) * @param array $where * @return mixed */ public function getCateList(array $where) { $list = $this->getList($where); $options = [['value' => 0, 'label' => '所有分类']]; foreach ($list as $id => $cateName) { $options[] = ['label' => $cateName['name'], 'value' => $cateName['id']]; } return $options; } /** * 保存新建的资源 * @param array $data * @return \qiniu\basic\BaseModel|\think\Model * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ public function save(array $data) { if ($this->getOne(['name' => $data['name'], 'relation_id' => $data['relation_id'] ?? 0])) { throw new AdminException('该分类已经存在'); } $res = $this->create($data); if (!$res) throw new AdminException('新增失败!'); return $res; } /** * 保存修改的资源 * @param int $id * @param array $data * @param string|null $key * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ public function update($id, array $data, ?string $key = null) { $attachment = $this->getOne(['name' => $data['name'], 'relation_id' => $data['relation_id'] ?? 0]); if ($attachment && $attachment['id'] != $id) { throw new AdminException('该分类已经存在'); } return parent::update($id, $data, $key); } /** * 删除分类 * @param int $id * @throws DbException */ public function del(int $id) { $count = $this->be(['pid' => $id]); if ($count) { throw new AdminException('请先删除下级分类!'); } else { $res = $this->delete($id); if (!$res) throw new AdminException('请先删除下级分类!'); } } }