function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
WesNolte__cWesNolte__c 

Dynamically fetching parent fields in a dynamic SOQL query

Hello,

 

I've run into some trouble trying to fetch related object fields from a dynamic query using SObjects e.g.

 

 

String qs = 'SELECT account.name FROM Contact LIMIT 1';
SObject s = database.query(qs);

String name = s.get('account.name'); // OR
SObject account = s.get('account');

 So neither of the bottom two lines execute and I really need to fetch that information out and into a generic SObject. Anyone have a solution?

 

Wes

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Ralph CallawayRalph Callaway

Hi Weznolte,

 

With Dynamic Apex you'll need to pull out the parent sobject first using the getSObject method and then do a second call to get the name.

 

SObject account = s.getSObject('account');
String name = (String) account.get('name');

 

 

All Answers

Ralph CallawayRalph Callaway

Hi Weznolte,

 

With Dynamic Apex you'll need to pull out the parent sobject first using the getSObject method and then do a second call to get the name.

 

SObject account = s.getSObject('account');
String name = (String) account.get('name');

 

 

This was selected as the best answer
WesNolte__cWesNolte__c

Cheers.