+ Start a Discussion
h8r41dh8r41d 

How to retrieve relationship fields from generic sobject or aggregate result objects

 

This is just some example code, I don't want the focus of what I'm doing to cloud the concept I'm trying to figure out.

 

code:

 

sobject[] something = [SELECT Contact.FirstName, Contact.Account.Name, contact.account.type from Contact];

 

I've used sobject[] here instead of contact[] because in my project the query is dynamic and could be from a different table.

 

My question is, how do I get the relationship field from this? Normally, I know you can do this:

 

string theName = something[0].Account.Name;

 

However, this results in the error: Field expression not allowed for generic SObject

 

How do I get around this?

Best Answer chosen by Admin (Salesforce Developers) 
ShamilShamil
SObject c = Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
String accountName = String.valueOf(c.getSObject('Account').get('Name'));
System.debug(accountName);

With custom relationships you'd use soemthing similar to:

s.getSObject('Your_Custom_Object__r').('Some_Field__c');

All Answers

ShamilShamil
SObject c = Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
String accountName = String.valueOf(c.getSObject('Account').get('Name'));
System.debug(accountName);

With custom relationships you'd use soemthing similar to:

s.getSObject('Your_Custom_Object__r').('Some_Field__c');

This was selected as the best answer
h8r41dh8r41d

Also, for the record, I figured out I can do this in visualforce :

 

{!something['Account']['Name']}

 

Just in case anyone else comes across this

vanessenvanessen
Thanks h8r41d, i was searching for this :)
AngulixAngulix
Excellent, helped me so much today !
 
WilmerWilmer
Hi, How would that be with multiple level relationships? 

i.e. Object1__r.Objectt2__r.Object3__r.Some_Field__c

It doesn't work for...  s.getSObject('Object1__r.Objectt2__r.Object3__r').('Some_Field__c');  ???
Naveen IlaNaveen Ila
Proto type : 

String objRelStr = 'Objectt2__r.Object3__r.Some_Field__c';
    
    List<String> objRelList = objRelStr.split('.');
    sObject s= Object1__r;
    for(Integer i=0; i< (objRelList.size() - 1); i++ ) {
        
        s = s.getSObject(objRelList[i]);
    
    }
    
    Sytem.debug(s.get('Some_Field__c'));