Retrieve related objects from Sobject

Salesforce Feb 28, 2015

Sometimes, while trying to make a generic query for multiple objects, a situation may arise where we don't want to typecast generic sObject to a particular object. At that time, it can be painful to retrieve related object information from SOQL queries.

Let's take a general scenario, you must be using a Dynamic SOQL query operating on multiple objects and storing results in sObject. Below are some examples:

  1. sObject sobj = database.query('SELECT Account.name ,id from contact limit 1');

  2. sObject sobj = database.query('SELECT id,(SELECT Name from contacts) from Account limit 1');

These query will give you the same results but cannot be accessed the same way as they do with defined objects (Account, Contact , Case etc.)

How to retrieve parent object information from sObject?

Scenario 1: contact con = [SELECT Account.name ,id from contact limit 1];
system.debug(con.Account.name);

Scenario 2: sobject sobj = [SELECT Account.name , id from contact limit 1];
system.debug(sobj.getsObject('Account').get('name'));

Above two statements have same result set but different ways to access them. Second Scenario uses 'getsObject' method to retrieve the parent record and then it's fields

How to retrieve Child objects from sObject?

Scenario 1: Account acc = [SELECT id,(SELECT Name from contacts) from Account limit 1] ;
system.debug(acc.contacts);

Scenario 2: sobject sobj2 = [SELECT id,(SELECT Name from contacts) from Account limit 1] ;
system.debug(sobj2.getsobjects('contacts'));

For retrieving child objects, 'getsObjects' is used . It depicts multiple related records should retrieve.

Salesforce link for these methods :
getSobject & getSobjectsMethod

Hope this will help!!

Related Tags:

Salesforce