Skip to content

Instantly share code, notes, and snippets.

@Sunil02kumar
Created August 11, 2019 03:49
Show Gist options
  • Save Sunil02kumar/5127a4cf50c6200c5baba52df1a04994 to your computer and use it in GitHub Desktop.
Save Sunil02kumar/5127a4cf50c6200c5baba52df1a04994 to your computer and use it in GitHub Desktop.
Accessing Child Records from sObjects in Dynamic Queries Using Dynamic Apex
String qstring ='Select id,Name,(select id,Lastname,Email from Contacts),(Select id,Name,Stagename from Opportunities) from Account where id=\'00190000004Awos\' Limit 1';
List<sobject> sobjectList = database.query(qstring);
for(sObject sb:sobjectList){
System.debug('****Parent record-Account details:'+sb.get('Name'));
//check if account has any contact child records
List<sobject> contactChildObjects = sb.getSobjects('Contacts');
System.debug('****Child Contact Records size:'+contactChildObjects.size());
if(contactChildObjects.size()>0){
for(sobject con:contactChildObjects){
system.debug('Contact Id:'+ con.get('Id'));
system.debug('Contact Lastname:'+ con.get('Lastname'));
system.debug('Contact Email:'+ con.get('Email'));
}
}
//check if account has any opportunities child records
List<sobject> oppChildObjects = sb.getSobjects('Opportunities');
System.debug('****opportunities Records size:'+oppChildObjects.size());
if(oppChildObjects.size()>0){
for(sobject con:oppChildObjects){
system.debug('opp Id:'+ con.get('Id'));
system.debug('opp Name:'+ con.get('Name'));
system.debug('opp Stage:'+ con.get('Stagename'));
}
}
}
@Arvindh061094
Copy link

what to do if we want to fetch all account and related contact and opportunity records without id and limit.Iam getting null pointer exception while trying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment