+ Start a Discussion
mworldmworld 

Locating Master/Detail and Lookup Relationships for a given Object

What are my options, if any, to programmatically determine what Master/Detail or Lookup relationships a particular Object is involved in?

 

We would like to prevent users from deleleting an Account (for example) that is involved in the above relationships. We would prefer not to hard code the existing relationships but rather determine them dynamically so that we don't need to continually update the code as we add objects to our system.

 

Ideas?

zachumenzachumen

The following will give you a list of all the child relationships:

 

sObject s = [some sObject]
Schema.SObjectType sType = s.getSObjectType();
Schema.DescribeSObjectResult R = sType.getDescribe();
List<Schema.ChildRelationship> C = R.getChildRelationships(); 

 

You can then used the methods described here to do whatever you need.

Starz26Starz26

Here is an example for two custom objects

 

FSA is child of IHO. No delete IHO if fsa exists

 

trigger IHO_onDelete on Implementation_Hand_Off__c(before delete){

Map<ID, Implementation_Hand_Off__c> mIHO = New Map<ID, Implementation_Hand_Off__c>(
           [Select ID, (Select ID From FSA2IHO__r) From Implementation_Hand_Off__c Where ID IN :trigger.old]);
       
       for(Implementation_Hand_Off__c i : trigger.old){
       
           for(FSA__c f : mIHO.get(i.id).FSA2IHO__r){
               i.addError('NoDelete');
               break;
           }
       
       }
}