3

I am working on Selector Layer and I would like to avoid situations where the relationship name is passed as a String.

My Goal

SELECT Account.Owner.Name FROM Opportunity 

Approach 1: Use getRelationshipName() method

The code below works as expected, but is quite complicated, and looks ugly.

System.debug(Opportunity.AccountId.getDescribe().getRelationshipName() + '.' + Account.OwnerId.getDescribe().getRelationshipName() + '.' + User.Name); 

Approach 2: Get relationship name from DescribeFieldResult Class

I would like to get entire relationship from DescribeFieldResult Class.

SObjectField myField = Opportunity.Account.Owner.Name; System.debug(myField.getDescribe().getSObjectField()); // Name System.debug(myField.getDescribe().getRelationshipName()); System.debug(myField.getDescribe().getLocalName()); // Name System.debug(myField.getDescribe().getReferenceTargetField()); System.debug(myField.getDescribe().getName()); // Name 

I tried all methods but failed.

Question

Is there any simple way to get a child-to-parent relationship name?

1
  • Note that a child could have multiple relationships to the same parent Commented Jan 17, 2024 at 19:56

1 Answer 1

1

Working from the SObjectType, the getChildRelationships method of DescribeSObjectResult provides an array of ChildRelationship records that provide the information you are likely looking for e.g. getRelationshipName. Which field is involved is returned by getField.

Obviously this is from the parent side, but you can write code to talk up or down the relationships.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.