How to Retrieve Data From Nested Fields in SOQL From a Map
If you've read my post on How to Efficiently Save Data from SOQL Queries, it's reasonable to assume that you've started using variables of type Map to store query results. Storing results in a map has clear advantages, but now you encounter a problem: your query contains nested fields, and you're not sure how to extract the data from these nested fields and store them in variables.
To understand the problem more clearly, let's look at the following example:
First, let's store our query's results in a map:
Map<Id, myCustomObjectA__c> allMyCustomRecords = new Map<Id, myCustomObjectA__c>([SELECT Id, CustomObjectB__c, CustomObjectB__r.Name, Account]);
Now, if we wanted to retrieve the ID from the CustomObjectB__c field, all we need to do is provide the ID of the desired record to the map's get
method like this:
allMyCustomRecords.get('myRecordID').CustomObjectB__c
But what if we wanted to retrieve the name of CustomObjectB? The previous approach won't work; instead, it will produce an error:
allMyCustomRecords.get('myRecordID').CustomObjectB__r.Name
The correct way to access the nested field Name is as follows:
allMyCustomRecords.get('myRecordID').getSObject('CustomObjectB__r').get('Name');
Or in a more general form:
Map.get(id).getSObject('FieldName__r').get('FieldName__c')
Please note! The example above refers to cases where the object from which you want to extract the nested field is a custom object you created in your environment, not a standard platform object like Account or User. In the case of standard objects, you would use the following structure:
Map.get(id).getSObject('FieldName').get('FieldName')
For example:
allMyCustomRecords.get('myRecordID').getSObject('Account').get('Name')