When I run the following SOQL query:
SELECT Id, ContactId, Contact.LastName FROM Opportunity
I get the following error on the Contact.LastName
field:
System.QueryException: Didn't understand relationship 'Contact' in field path.
Even though ContactId is a Lookup field, the relationship is not recognized. Why?
Noteworthy
Opportunity.ContactId
represents the Contact record that was created when a lead was converted and an Opportunity was created as a result.
You can dynamically check if a lookup field's relationship is valid with following check:
Opportunity.AccountId.getDescribe().getReferenceTo(); // (Account) - Is a lookup field
Opportunity.AccountId.getDescribe().getRelationshipName(); // Account - As expected
Opportunity.ContactId.getDescribe().getReferenceTo(); // (Contact) - Is a lookup field
Opportunity.ContactId.getDescribe().getRelationshipName(); // null - strange...
system.debug(Opportunity.ContactId.getDescribe().getReferenceTo());
throws compilation error, as well as invalid SOQL query forselect id, ContactId from Opportunity
. Anyway, itis clearly understandable, because Opportunity and Contacts have many-to-many relationship realized through OpportunityContactRole.