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
Priyanka Pawar 4Priyanka Pawar 4 

Fetch child records in self relationship

I have a User Record and ManagerId field in It.Given a particular User ID i want to get all users under the given user ID at all levels.
Is this possible in apex.This is not related to Role hierarchy.
GauravGargGauravGarg
Hi Priyanka,

Do you need all the user's list having same ManagerId?

Thanks,
Gaurav
Shreyas Shah 9Shreyas Shah 9
Hi ,
below script give you full role hierarchy.
so you can manage same with user record ID and where clause in SOQL.
Global class RoleLog{
 		Global string Name ;
 		Global String RoleId;
 		Global Boolean leaf;
 		Global set<RoleLog> SubordinateRoles;
	}
	// call this method with inputparm = user RoleID
Global Static Set<RoleLog> getRoleHierarchy(){
	    List<UserRole> AllRole = [select Id,Name, ParentRoleId from UserRole ORDER BY ParentRoleId ASC NULLS FIRST LIMIT 999];
	    set<RoleLog> RoleHierarchy = new set<RoleLog> ();
	    integer count = 1;
	    for(UserRole Role : AllRole){
	        if(count==1){
	            count++;
	            RoleLog TempRole = New RoleLog();
	                TempRole.RoleId = Role.ParentRoleId ;
	                TempRole.Name = 'RoleHierarchy';
	                TempRole.leaf = false;
	                TempRole.SubordinateRoles = getSubordinateRoles(TempRole.RoleId,AllRole);
	            RoleHierarchy.add(TempRole);
	        } // End OF IF
	    } // End Of For
	    return RoleHierarchy;
	} // End of Method
	/* this method use for sub child of role */
	Global Static Set<RoleLog> getSubordinateRoles(String PID, List<UserRole> rolelist){
	    set<RoleLog> remainingSubordinateRoles = new set<RoleLog> ();
	    for(UserRole children: rolelist){
	        if(children.ParentRoleId == PID){
	            RoleLog TempRole1 = New RoleLog();
	                TempRole1.RoleId = children.ID ;
	                TempRole1.Name = children.Name;
	                TempRole1.leaf = false;
	                TempRole1.SubordinateRoles = getSubordinateRoles(TempRole1.RoleId,rolelist);
	                if(TempRole1.SubordinateRoles.size() == 0){
                		TempRole1.leaf = true;
                	}
            	remainingSubordinateRoles.add(TempRole1);
        	} // End of IF
    	} // End of For
    	return remainingSubordinateRoles;
	} // End of Method

 
Priyanka Pawar 4Priyanka Pawar 4
not just the users one level down.I want all users under the given manager at all levels.For example A will be maanger of B.B will be the manager of C and D.C might be the Manager of E and so On.
GauravGargGauravGarg
Hi Priyanka,

I would provide you the solution by tommorow EOD.

Thanks,
Gaurav