function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SambitNayakSambitNayak 

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

Hi,
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];
            
            if(wkAlList.size()>0){
                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){
     conIdToWorkAllocationMap.put(conObj.id,conObj.Work_Allocations__c); 
}


        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!
Regards,
Suraj Tripathi