9

I have a field Board_Name__c that is a lookup from Opportunity back to Opportunity. How can I dynamically find out that Opportunity.Board_Name__c references the Opportunity sObject while Opportunity.Account references the Account sObject?

  • 2
    One way to do it would be a soql query to select a row and using the Id.getSObjectType() method on the Id held in each lookup field to get the sObject type. – techtrekker Dec 4 '13 at 1:48
  • Thanks techtrekker, but I'm trying to figure this out when there are no pre-existing relationships. If I have a not-yet-committed new sObject, I'd like to be able to tell the reference object for a given reference field (no Id is present if the records are not yet committed...) – Nathan Williams Dec 4 '13 at 14:35
10

In the describe for the Field there's a referenceTo property which indicates which type(s) the foreign key is for, e.g.

system.debug(Schema.SObjectType.Contact.fields.AccountId.referenceTo[0].getDescribe().getName());

prints Account

The docs have a section on the describe functionality

  • Awesome, that never showed up when I looked up Schema.DescribeFieldResult on Google... Thanks! Also, I was specifically asking about dynamic apex and how to get it to a string (what you have above returns a List<Schema.SObjectType>: I have a map (Map<String, Map<String, Schema.SObjectField>>) called mapSObjectFields, and the correct nomenclature from there was: mapSObjectFields.get(sObjectName).get(relationshipName).getDescribe().referenceTo[0].getDescribe().getName() I am worried about the double "getDescribe()" required here... Any better way? – Nathan Williams Dec 4 '13 at 14:34
  • Salesforce officially got rid of "describe" limits, so this is a non-issue! – Nathan Williams Feb 27 '16 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.