private static Set<Id> getSubordinateRoleIds(Id roleId) {
Set<Id> roleIds = new Set<Id>();
roleIds.add(roleId);
List<UserRole> subRoles = [SELECT Id FROM UserRole WHERE ParentRoleId = :roleId];
for (UserRole subRole : subRoles) {
roleIds.addAll(getSubordinateRoleIds(subRole.Id));
}
return roleIds;
}
public static List<String> getSubordinateUserIds(Id UserId) {
// 获取当前用户
User currentUser = [SELECT Id, UserRoleId FROM User WHERE Id = :UserId];
// 获取当前用户的角色及其所有下级角色
Set<Id> accessibleRoleIds = new Set<Id>();
if (currentUser.UserRoleId != null) {
accessibleRoleIds = getSubordinateRoleIds(currentUser.UserRoleId);
}
List<User> users = [SELECT Id, Name FROM User WHERE UserRoleId IN :accessibleRoleIds];
List<String> userIds = new List<String>();
// 将用户和他们的 KPI 记录关联起来
for (User user : users) {
userIds.add(user.Id);
}
System.debug('userIds '+userIds);
return userIds;
}
不过由于递归,很容易超过 100 次 SOQL 查询的限制,故一般不使用,而是使用判断上下级函数。见另一篇文章:https://blog.csdn.net/lycwhu/article/details/140847991