SystemCategoryLogic.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. namespace plugin\saiadmin\app\logic\system;
  8. use plugin\saiadmin\basic\think\BaseLogic;
  9. use plugin\saiadmin\exception\ApiException;
  10. use plugin\saiadmin\app\model\system\SystemCategory;
  11. use plugin\saiadmin\utils\Helper;
  12. use plugin\saiadmin\utils\Arr;
  13. /**
  14. * 附件分类逻辑层
  15. */
  16. class SystemCategoryLogic extends BaseLogic
  17. {
  18. /**
  19. * 构造函数
  20. */
  21. public function __construct()
  22. {
  23. $this->model = new SystemCategory();
  24. }
  25. /**
  26. * 添加数据
  27. */
  28. public function add($data): bool
  29. {
  30. $data = $this->handleData($data);
  31. return $this->model->save($data);
  32. }
  33. /**
  34. * 修改数据
  35. */
  36. public function edit($id, $data): bool
  37. {
  38. $data = $this->handleData($data);
  39. if ($data['parent_id'] == $id) {
  40. throw new ApiException('上级分类和当前分类不能相同');
  41. }
  42. if (in_array($id, explode(',', $data['level']))) {
  43. throw new ApiException('不能将上级分类设置为当前分类的子分类');
  44. }
  45. $model = $this->model->findOrEmpty($id);
  46. if ($model->isEmpty()) {
  47. throw new ApiException('数据不存在');
  48. }
  49. return $model->save($data);
  50. }
  51. /**
  52. * 数据删除
  53. */
  54. public function destroy($ids): bool
  55. {
  56. $num = $this->model->where('parent_id', 'in', $ids)->count();
  57. if ($num > 0) {
  58. throw new ApiException('该部门下存在子分类,请先删除子分类');
  59. } else {
  60. return $this->model->destroy($ids);
  61. }
  62. }
  63. /**
  64. * 数据处理
  65. */
  66. protected function handleData($data)
  67. {
  68. if (empty($data['parent_id']) || $data['parent_id'] == 0) {
  69. $data['level'] = '0';
  70. $data['parent_id'] = 0;
  71. } else {
  72. $parentMenu = SystemCategory::findOrEmpty($data['parent_id']);
  73. $data['level'] = $parentMenu['level'] . $parentMenu['id'] . ',';
  74. }
  75. return $data;
  76. }
  77. /**
  78. * 数据树形化
  79. * @param array $where
  80. * @return array
  81. */
  82. public function tree(array $where = []): array
  83. {
  84. $query = $this->search($where);
  85. $request = request();
  86. if ($request && $request->input('tree', 'false') === 'true') {
  87. $query->field('id, id as value, category_name as label, parent_id, category_name, sort');
  88. }
  89. $query->order('sort', 'desc');
  90. $data = $this->getAll($query);
  91. return Helper::makeTree($data);
  92. }
  93. }