0

Instead of teacher__c and student__c, they needs be dynamic variables. How can I substitute these API names with variables: parentApiName and childApiName?

for (ChildRelationship relation : SObjectType.teacher__c.getChildRelationships())
    if (relation.getChildSObject() == student__c.sObjectType)
        system.debug(relation.getRelationshipName());

What I tried and failed:

for (ChildRelationship relation : SObjectType.${parentApiName}.getChildRelationships())
    if (relation.getChildSObject() == `${childApiName}.sObjectType`)
        system.debug(relation.getRelationshipName());

1 Answer 1

1

You can get Schema information dynamically by leveraging some of the dynamic Schema methods like describeSObjects which takes a list of strings. I've taken your code and written a method that accepts the parent type and child type dynamically and returns the relationship name, if one exists.

public static String getRelationshipName(String parentObjectApiNames, String childObjectApiName)
    List<Schema.DescribeSObjectResult> result = Schema.describeSObjects(new List<String>{parentObjectApiNames});

    for (ChildRelationship relation : result[0].getChildRelationships()) {
        if (relation.getChildSObject().getDescribe().getName() == childObjectApiName) {
            return relation.getRelationshipName();
        }
    }

    return null;
}
2
  • @ nbrown Works great thanks!
    – ApexCowboy
    Commented Oct 27, 2021 at 20:50
  • Good to hear! If this answers your question then please accept it. Also, it's worth noting that schema methods can be resource intensive at times, so this method is a prime candidate for memoization so that way, should you need to call it multiple times, you don't need to walk all of the relationships on an object and instead put them all in a map for subsequent calls.
    – nbrown
    Commented Oct 28, 2021 at 14:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .