How to identify relationship type (Lookup / Master detail) from the field api Name in APEX?

I have requirement in which i iterate through all fields of sObject and needs to identify fields which has master detail relation ship only and then get that (Reference to)object name and then further logic.

so, I need help to get Name of this Master Object.

what i am trying to do it now is,

//here, key is comming from iteration over a map which is String.
Schema.SObjectType objectType = Schema.getGlobalDescribe().get(Key);  // sObject token 
Map<String, Schema.SObjectField> fieldMapForChild = objectType.getDescribe().fields.getMap();

for (String fieldNameChild : fieldMapForChild.keySet()) { 
    Schema.SObjectField fieldChild = fieldMapForChild.get(fieldNameChild);      //field token
    Schema.DisplayType FldTypeChild = fieldChild.getDescribe().getType();       //type of field.
    String fieldTypeChild = String.valueOf(FldTypeChild);                       //string value of type.

    Schema.DescribeFieldResult dfr1 = fieldMapForChild.get(fieldNameChild).getDescribe();   

    //Here , I want fields which has Master detail relation ship and name of that Master Object.
    if(fieldTypeChild == 'REFERENCE' ){  // this will true for lookup and master detail both.
        String RelatedObjNameChild = String.valueOf(dfr1.getReferenceTo()).substringBetween('(',')');  // Related Object name
    }
}

Answer

You should use the getRelationshipOrder() method available in the DescribeFieldResult class. This is populated only for Master-Detail relationships and is null for lookup relationships.

RelationShipOrder : The type of relationship for a master-detail relationship field. Valid
values are:

  • 0 if the field is the primary relationship
  • 1 if the field is the secondary relationship

Also, to get the name of the Master Object, you need to use the getReferenceTo() method.

getReferenceTo() : Returns a list of Schema.sObjectType objects for the
parent objects of this field. If the isNamePointing method returns
true, there is more than one entry in the list, otherwise there is
only one.

Hope this helps. 🙂

Attribution
Source : Link , Question Author : Tejas Kapasi , Answer Author : Rajiv Bhatt

Leave a Comment