Sunday 7 July 2019

Related reference Fields Value in sObject SOQL


In Dynamic SOQL we create query string using Apex code at run time and use Database.Query method to fetch the results.

example: 
String queryString = ' SELECT Id, Name, AccountId FROM Contact LIMIT 1';
sObject result = Database.query(queryString);

above query will return me a contact information, if I wanted to access record's Name I can access it using sObject get() method i.e. result.get('Name') will give me Name value.




Output:


But the real challenge we will face when you try to access fields value from related object field, i.e. if you try to access Account.AnnaualRevenue you will get an exception 'System.SObjectException: Invalid field Account.AnnualRevenue for Contact'.

To fix this we we will use getSObject() method to traverse the relationship.

below code will traverse the relationship and get you the value:

References: sObject Class, String Class, Martin Borthiry

No comments:

Post a Comment