+ Start a Discussion

How do I iterate over the child objects without using SELECT query

I have the contact object. Work Allocation is a custom child object of Contact.
How do I iterate over these child records without using SELECT query inside the FOR loop.
My Trigger handler code is here. Although it's working fine, I know it's not bulkified. Please help:


    public static void checkWorkAlloc(List<Work_Allocation__c> workAllocList){
        for (Work_Allocation__c wk : workAllocList){
            //Collect the work allocation records under the parent Contact in an array
            Work_Allocation__c[] wkAlList=[SELECT Id, Start_Date__c, End_Date__c FROM Work_Allocation__c WHERE Contact_Resource__c =: wk.Contact_Resource__c];
                for (Integer i=0; i < wkAlList.size(); i++){
                Work_Allocation__c workAlloc1=wkAlList[i];

Suraj Tripathi 47Suraj Tripathi 47
Hi Sambit,

please try below code
public static void checkWorkAlloc(List<Work_Allocation__c> workAllocList){
      set<id> conIdSet = new set<id>();
      for(Work_Allocation__c wAObj :workAllocList){
     conIdSet.add(wAObj. Contact_Resource__c);}

list<contact> conList = [select id,(select id from Work_Allocations__c) from contact where id In:conIdSet];

map<id,list<Work_Allocation__c>> conIdToWorkAllocationMap = new map<id,list<Work_Allocation__c>>();
for(contact conObj:conList){

        for (Work_Allocation__c wk : workAllocList){
           if(conIdToWorkAllocationMap .containsKey(wk.Contact_Resource__c) && conIdToWorkAllocationMap.get(wk.Contact_Resource__c).size()>0 ){

//write your logic here 

If you find your Solution then mark this as the best answer.

Thank you!
Suraj Tripathi