function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Akash Shinde 34Akash Shinde 34 

In role hierarchy, how to access only the immediate lower level user's list(not the nested level user's list) through soql query ?

Below code retrieves all nested level user's Id list. Need to retrieve only immediate lower level user's Id list.
public with sharing class RoleUtils {
	
  public static Set<ID> getRoleSubordinateUsers(Id userId) {
  	
    // get requested user's role
    Id roleId = [select UserRoleId from User where Id = :userId].UserRoleId;
    // get all of the roles underneath the user
    Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId});
    // get all of the ids for the users in those roles
    Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where 
      UserRoleId IN :allSubRoleIds]);
    // return the ids as a set so you can do what you want with them
    return users.keySet();
  	
  }
	
  private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {
  	
    Set<ID> currentRoleIds = new Set<ID>();
    
    // get all of the roles underneath the passed roles
    for(UserRole userRole :[select Id from UserRole where ParentRoleId 
      IN :roleIds AND ParentRoleID != null])
    currentRoleIds.add(userRole.Id);
    
    // go fetch some more rolls!
    if(currentRoleIds.size() > 0)
      currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));

    return currentRoleIds;
    
  }

}

 
Best Answer chosen by Akash Shinde 34
Adilson Arcoverde JrAdilson Arcoverde Jr
Hi Akash,

You just need to remove your recursive call in line 28, because you wan't to get just one children level. Your code should be like this:
 
public with sharing class RoleUtils {
	
  public static Set<ID> getRoleSubordinateUsers(Id userId) {
  	
    // get requested user's role
    Id roleId = [select UserRoleId from User where Id = :userId].UserRoleId;
    // get all of the roles underneath the user
    Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId});
    // get all of the ids for the users in those roles
    Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where 
      UserRoleId IN :allSubRoleIds]);
    // return the ids as a set so you can do what you want with them
    return users.keySet();
  	
  }
	
  private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {
  	
    Set<ID> currentRoleIds = new Set<ID>();
    
    // get all of the roles underneath the passed roles
    for(UserRole userRole :[select Id from UserRole where ParentRoleId 
      IN :roleIds])
    currentRoleIds.add(userRole.Id);
    
    // go fetch some more rolls!
    //if(currentRoleIds.size() > 0)
    //  currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));

    return currentRoleIds;
    
  }

}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help other too.

Regards.