Print this page

How to create a Map of parent-child SOQL query within Apex ?


Knowledge Article Number: 000163406


Description
Requirement : Convert a query into Map Parent-Child SOQL Query : [SELECT id, (SELECT Lead__c FROM Lead.R00N30000001MXeWEAW__r) FROM Lead where id IN : leadId ];


Resolution
Below mentioned is the sample code which shows that how we can achieve the above requirement :

Lead-  Parent object (Standard)

IndividualEmailResult__c - Child Object(Custom)

Sample Code:-
===========

Map<id,List<IndividualEmailResult__c>> mapofleadEmailresult = new Map<id,List<IndividualEmailResult__c>>(); 

List<Lead> leads= [SELECT id, (SELECT Lead__c FROM Lead.R00N30000001MXeWEAW__r) FROM Lead where id IN : leadId ]; 

for(Lead l : leads) 

for(List<IndividualEmailResult__c> e : l.R00N30000001MXeWEAW__r) 

mapofleadEmailresult.put(l.id, e);