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
  • 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. Commented Dec 4, 2013 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...) Commented Dec 4, 2013 at 14:35

1 Answer 1

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

2
  • 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? Commented Dec 4, 2013 at 14:34
  • Salesforce officially got rid of "describe" limits, so this is a non-issue! Commented Feb 27, 2016 at 21:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .