flipped-aurora/gin-vue-admin · error

该部门下存在用户,不允许删除

Error message

该部门下存在用户,不允许删除

What it means

DeleteSysDepartment refuses to delete a department that still has users whose primary dept_id points at it. After the child-department check, it counts sys_user rows with dept_id = id and blocks deletion when userCount > 0.

Source

Thrown at server/service/system/sys_department.go:138

		"leader_id": dept.LeaderId,
		"status":    dept.Status,
	}).Error
}

// DeleteSysDepartment 删除部门, 存在子部门或已有用户归属时禁止删除
func (s *SysDepartmentService) DeleteSysDepartment(ctx context.Context, id uint) (err error) {
	if id == 0 {
		return errors.New("部门ID不能为空")
	}
	if !errors.Is(global.GVA_DB.WithContext(ctx).Where("parent_id = ?", id).First(&system.SysDepartment{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在子部门,不允许删除")
	}
	var userCount int64
	if err = global.GVA_DB.WithContext(ctx).Model(&system.SysUser{}).Where("dept_id = ?", id).Count(&userCount).Error; err != nil {
		return err
	}
	if userCount > 0 {
		return errors.New("该部门下存在用户,不允许删除")
	}
	var joinCount int64
	if err = global.GVA_DB.WithContext(ctx).Model(&system.SysUserDepartment{}).Where("sys_department_id = ?", id).Count(&joinCount).Error; err != nil {
		return err
	}
	if joinCount > 0 {
		return errors.New("该部门下存在用户,不允许删除")
	}
	return global.GVA_DB.WithContext(ctx).Delete(&system.SysDepartment{}, id).Error
}

// GetSysDepartment 获取单个部门
func (s *SysDepartmentService) GetSysDepartment(ctx context.Context, id uint) (dept system.SysDepartment, err error) {
	err = global.GVA_DB.WithContext(ctx).Preload("Leader").First(&dept, id).Error
	return
}

// GetSysDepartmentTree 获取部门树; 带名称搜索时平铺返回匹配项, 否则返回整棵树

View on GitHub (pinned to 3136500ef3)

Solutions

  1. Reassign those users to another department (update their dept_id, e.g. via user edit or SetDepartmentUsers) before deleting
  2. Use the department member management page to move users out first
  3. Delete or reassign the users if they are no longer needed
Defensive patterns

Strategy: validation

Validate before calling

var userCount int64
global.GVA_DB.Model(&system.SysUser{}).Where("dept_id = ?", id).Count(&userCount)
if userCount > 0 {
    return fmt.Errorf("%d users still assigned to this department", userCount)
}

Try / catch

if err := deptService.DeleteSysDepartment(ctx, id); err != nil {
    if err.Error() == "该部门下存在用户,不允许删除" {
        // route users to the member-reassignment flow
    }
    return err
}

Prevention

When it happens

Trigger: Deleting a department where one or more sys_user rows have dept_id equal to that department ID.

Common situations: Users were assigned to the department as their main department; bulk user import set dept_id; admin tries to remove an active team department.

Related errors


AI-assisted analysis of flipped-aurora/gin-vue-admin@3136500ef3 (2026-08-31). Data as JSON: /api/errors/ad470b85eec536d2. Report an issue: GitHub.