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?
-
2One 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.– techtrekkerCommented 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...)– Nathan WilliamsCommented Dec 4, 2013 at 14:35
Add a comment
|
1 Answer
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? 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