+ Start a Discussion
Starz26Starz26 

A Pattern for Obtaining all record in a Hierarchy

Greetings,

 

I wrote this little loop while trying to get a list of ALL accounts within a Hierachy regardless of there in the hierachy you start from.

 

For example

A

-----b

-----------b1

-----c

-----------c1

---------------c1.2

-----d

 

So if I start at b1, it will return all accounts up to A and back down thus including c1.2 as well.

 

Maybe someone will find it useful. You could refactor it to work with roles or only go up 1 level to find parent and siblings, etc...

 

 

Account theAccount = //Your SOQL Here
Set<ID> AllParents = new Set<ID>();
Boolean allDone;

AllParents.add(theAccount.ID);
      //If the account we are starting at has a Parent ID, add it
      //to the set of IDs
      if(theAccount.ParentID != Null){
        AllParents.add(theAccount.ParentID);
      }
      
      //Main loop to traverse through the Hierarchy
      do{
         //Set the flag to indicate loop should stop
         allDone = true;
        //Get a list of accounts with IDs or Parent IDs in the AllParents Set
        //This will produce 1 SOQL for each level in the Hierachy 
        //Max is then 99 levels deep which I believe no one will  have
        //You could add a check though
        for(Account a : [Select ID, ParentID From Account Where ID IN :AllParents OR ParentID IN :AllParents]){

          if(!AllParents.contains(a.ID) || ( !AllParents.contains(a.parentID) && a.parentID != null)){

            if(a.parentID != null)
              AllParents.add(a.parentID);

            AllParents.add(a.id);
            //Reset flag to find more parents / children
            allDone = false;

          }
          
        }
        
      } while(allDone == false);