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

Referencing child data from a master-child Select statement (Relationship query)

My client has set up a custom object named Industry_Type__c that is a child object of the Account record.  The child relationship name is "IndustryTypes."  To make things confusing, this custom object has a field that is also named Industry_Type__c.

I'm writing some unit test code like this:
Id acctID = lcr.getAccountId();
Account acct = [select Id, Name, (select Industry_Type__c from IndustryTypes__r) 
from account where Id = :acctID];

 No errors.  The problem is, I can't figure out how to reference the Industry Type field value using dotted notation or any other way.

Here are the things I've tried:
String testval = acct.Industry_Type__c.Industry_Type__c;
String testval = acct.IndustryTypes.Industry_Type__c;
String testval = acct.IndustryTypes__r.Industry_Type__c;
String testval = acct.IndustryType__r.Industry_Type__c;
Industry_Type__c[] test = acct.IndustryTypes;

The first 4 attempts give me "Invalid foreign key relationship" errors, and the last one throws "Invalid Field IndustryTypes".

I've read page 28 and page 53 of the Apex Reference Manual and read the online SOQL doc but I still don't understand how I can do this.  Do I need to use queryResult()?|SkinName=webhelp

I believe child relationships are returned as lists or arrays.  The code should look something like this:

Account act = [select Id, Name, (Select Industry_Type__c from IndustryTypes__r) from Account where id =: lcr.getAccountId()];

//-- act will have potentially multiple 'IndustryType' records...
for(IndustryType__c it : act.IndustryTypes__r){
    //-- do something with the Industry_Type__c field
    System.debug('>> Industry_Type__c: '+it.Industry_Type__c);

//-- If you are expecting only a single IndustryType record then you could do this
if( act.IndustryTypes__r != null && act.IndustryTypes__r.size() > 0 ){
//-- do something
System.debug('>> Industry_Type__c: '+act.IndustryTypes__r[0].Industry_Type__c);