Skip to main content The Trailblazer Community will be unavailable from 2/1/2025 to 2/2/2025. Please plan your activities accordingly.

I m having a senerio where it is need to make a SOQL querry inside the FOR loop, but is increasing number of SOQL hits..

I m trying to use MAP but enable produce the required code... requesting to please guide/help me out for the same..

thanks

 

below is the code snippet...

public list<cNodes> getmainnodes()

   hierarchy = new list<cNodes>();

   List<Territory2> tempparent = [SELECT  Id, Name, ParentTerritory2Id, ParentTerritory2.Name from Territory2 order by ParentTerritory2.Name, Name];

   for (Integer i =0; i< tempparent.size() ; i++)

     {

         List<UserTerritory2Association> tempchildren = [SELECT  Id, Territory2.Name, User.Name, UserId from UserTerritory2Association where Territory2Id= :tempparent[i].Id order by Territory2.Name];

         hierarchy.add(new cNodes(tempparent[i],tempchildren));

     }   

   return hierarchy;

}
5 answers
  1. Apr 29, 2016, 3:58 AM
    @Sunny

    You can use this pseudo code

    public list<cNodes> getmainnodes(){

       hierarchy = new list<cNodes>();

       //get parentId, object map

       Map<Id,Territory2> tempparentMap = [SELECT  Id, Name, ParentTerritory2Id, ParentTerritory2.Name from Territory2 ];

    //get all children list

       List<UserTerritory2Association> tempchildren = [SELECT  Id, Territory2Id,Territory2.Name, User.Name, UserId from UserTerritory2Association where Territory2Id=:tempparentMap.keyset()];

    //Create parentId children list map

     Map<String,List<UserTerritory2Association>> parentIdChildrenMap = new Map<String,List<UserTerritory2Association>>();

            for(UserTerritory2Association child:tempchildren ){

                if(!parentIdChildrenMap.containsKey(child.Territory2Id)){

                    List<UserTerritory2Association> newObjectList = new List<UserTerritory2Association>();

                      parentIdChildrenMap.put(child.Territory2Id, newObjectList );

                    }

                   

               List<UserTerritory2Association> objectList =  parentIdChildrenMap.get(child.Territory2Id);

                objectList.add(child);             

            }

    //Create hierarchy list

    for(Id parentId:tempparentMap.keyset()){

          hierarchy.add(new cNodes(tempparentMap.get(parentId),parentChildrenMap.get(parentId)));

    }

       return hierarchy;

    }

     
Loading
0/9000