How to check the relationship type(Master-Detail or Lookup) using Salesforce Apex?

How to check the relationship type(Master-Detail or Lookup) using Salesforce Apex?

getRelationshipOrder() method from the DescribeFieldResult class can be used to check the relationship type(Master-Detail or Lookup) using Salesforce Apex.

getRelationshipOrder() return value will be null for Lookup relationships. getRelationshipOrder() will be populated only for the Master-Detail relationship.

getRelationshipOrder() return value will be

  1. 0 for the primary relationship.
  2. 1 for the secondary relationship.
  3. null if they are not Master Detail relationship.

Note:
For standard Master-Detail relationships fields, getRelationshipOrder() will return null.

Examples:

Integer intChild =
	Salary__c.Employee__c.getDescribe().getRelationshipOrder();
System.debug(
	'Employee and Salary is ' + 
    intChild
);

intChild =
	Contact.AccountId.getDescribe().getRelationshipOrder();
System.debug(
	'Account and Contact is ' + 
    intChild
);

intChild =
	Entitlement.AccountId.getDescribe().getRelationshipOrder();
System.debug(
	'Account and Entitlement is ' + 
    intChild
);

intChild =
    Quote.OpportunityId.getDescribe().getRelationshipOrder();
System.debug(
	'Opportunity and Quote is ' + 
    intChild
);

intChild =
    QuoteLineItem.QuoteId.getDescribe().getRelationshipOrder();
System.debug(
	'Quote and QuoteLineItem is ' + 
    intChild
);

Leave a Reply