0

Can anyone tell me how to get the Id of all managers based on the user Id? user-->manager1-->manager2-->manager3--->manager4

I wanna get all manager id

My code is:

public static List<Id> getParrentId(Id i){
    List<Id> ParentUserId=new List<Id>();
    User ur = new User();
    ur = [select Id, Name, ManagerId from User  where Id =: i];

    if(ur.ManagerId != null)        
        ParentUserId.addAll(getParrentId(ur.ManagerId));
    return ParentUserId;
 }

But it does not gather all manager id

Thanks in advance Karthick

6

You can make user of SOQL's ability to query multiple levels up the parent hierarchy (5 max) in a single query like this:

User u = [
        select
                Id,
                Name,
                Manager.Id,
                Manager.Manager.Id,
                Manager.Manager.Manager.Id,
                ...
         from User
         where Id = :i
         ];
Set<Id> ids = new Set<Id>();
// If reference field is null there is no manager so must check to avoid NPEs
if (u.Manager ! null) {
    ids.add(u.Manager.Id);
    if (u.Manager.Manager != null) {
        ids.add(u.Manager.Manager.Id);
        ...
    }
}
return ids;

If you need to go up more levels you will have to make an additional query per block of levels.

1
  • This seems the safest approach for the current possible answers, though it doesn't look very pretty. Still +1 – Double A Aug 27 '14 at 15:46
1

This version seems to be working

List<Id> ParentUserId=new List<Id>();
getParrentId(<userId>);
system.debug(ParentUserId);
public static void getParrentId(Id i){    
    User ur = new User();
    ur = [select Id, Name, ManagerId from User  where Id =: i];
    if(ur.ManagerId != null){        
        ParentUserId.add(ur.managerId);
        getParrentId(ur.ManagerId);
    }
}

I have moved the list declaration outside the method and changed the return type to void.

1
  • Need to be careful here for SOQL in recursion. – Plymouth Rock Jan 17 '19 at 10:23
0

I have posted an answer before that is a query Hierarchy that can query both up and down the role / account / user hierarchy. This may or may not help depending on your situation and you will need to modify slightly to use User instead of account but it will allow query up to 100 levels (although you will want to limit is less than that)

Apex or Visualforce way to get a list of queue a user is member of

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.