+ Start a Discussion

A Pattern for Obtaining all record in a Hierarchy



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









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;

      //If the account we are starting at has a Parent ID, add it
      //to the set of IDs
      if(theAccount.ParentID != Null){
      //Main loop to traverse through the Hierarchy
         //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)

            //Reset flag to find more parents / children
            allDone = false;

      } while(allDone == false);