Friday, February 14, 2020

How to access the child records from sObject using apex in Salesforce

Sometimes we run the dynamic query based on different inputs at the time we store the data in sObject or list<sObject>
from that data sometimes we have to get the child records info, to get the child records info use the
getSobject('<relationshipName>') or getSobjects('relationshipname')

Note
 custom object relationships you would use the something similar to
sObj.getSObject('Your_Custom_Object__r')

Sample Code
sObject sObj = [SELECT Id, Name, Account.Name, Account.Owner.Name FROM Contact WHERE Id = '003B000000FgA2JIAV'];

String strContactName = (String)sObj.get('Name');
String strAccName = (String)sObj.getSobject('Account').get('Name');
String strAccOwnerName = (String)sObj.getSobject('Account').getSobject('Owner').get('Name');

System.debug('Contact Name ====> '+strContactName);
System.debug('Account Name ====> '+strAccName);
System.debug('Account Owner Name ====> '+strAccOwnerName);

Output

1 comment:

  1. Good Example @Shaik Nagajani Sir, if I need to access the child records of same object how can we do that like below one:
    Sobject rec = [select Name, Phone, (select Name, Phone from ChildAccounts) from Account where Id='0019l00000qwevghuo'];

    ReplyDelete