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
Robert Davis 16Robert Davis 16 

SOQL Query from Custom Object Child to Standard Object Parents

I am attempting to use a SOQL query to query a Grandparent Object (Account), Parent Object (Opportunity), Child Custom Object (EBR_Form__c) but continue to get the following error in the Developer Console's Query Editor: 
 
SELECT id, Name, Opportunity__r.Name, Opportunity__r.Account.Name FROM EBR_Form__c

SELECT id, Name, Opportunity__r.Name, Opportunity__r.Account.Name
                                 ^
ERROR at Row:1:Column:18
Didn't understand relationship 'Opportunity__r' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.

User-added image

What am I missing. Your help would be appreciated greatly.
 
Best Answer chosen by Robert Davis 16
Leo10Leo10
Hi Robert Davis
You can write your code like this 
SELECT id, Name, <Field API Name of EBR_Form__c>__r.Name, <Field API Name of EBR_Form__c>.Account.Name FROM EBR_Form__c

you have to write Field API Name of EBR_Form__c + __r instead of Opportunity__r​ 

eg: SELECT id, Name, lookupToOpp__r.Name,lookupToOpp​.Account.Name FROM EBR_Form__c

Thank you
 

All Answers

EldonEldon
Hi Robert,

Make sure the name of the lookup field in your custom object is opportunity. If it is then please provide a screenshot of your custom object edit page.

Regards
Leo10Leo10
Hi Robert Davis
You can write your code like this 
SELECT id, Name, <Field API Name of EBR_Form__c>__r.Name, <Field API Name of EBR_Form__c>.Account.Name FROM EBR_Form__c

you have to write Field API Name of EBR_Form__c + __r instead of Opportunity__r​ 

eg: SELECT id, Name, lookupToOpp__r.Name,lookupToOpp​.Account.Name FROM EBR_Form__c

Thank you
 
This was selected as the best answer
Robert Davis 16Robert Davis 16
Thank you. I had always thought it was the name of the Object underscore underscore r but it is actually the name of the field. I get now. Thanks so very much to both Nabeel Kt and Eldon for the help.