Posted in Salesforce

Salesforce Apex : Dynamic SOQL Querying with uncertain relationship

Queries that involve complex relationship can be handled easily using List Methods.

Say, the query is something like this

List sobjectList = new List([SELECT GrandParent__r.Parent1__r.Id, GrandParent__r.Parent2__r.Name, GrandParent__r.Parent3__r.customField__c FROM SObject__c]);

When you want to check the Parent field, but using variable, you can use getSObject() and get() list methods:

String Parent = 'Parent2';
String field = 'Name';
System.debug(sbojectList[0].getSObject('GrandParent__r').getSObject(Parent + '__r').get(field));

This is equal to selecting like:


Following way is also allowed:

System.debug(sbojectList[0].GrandParent__r.getSObject(Parent + '__r').get(field));

But not like this:

System.debug(sbojectList[0].getSObject('GrandParent__r').getSObject(Parent + '__r').Name;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s