Like many SFDC developers, we have SObjects which are related to other custom relationships.

So, for example, MyCustomObject__c could have a relationship with MyCustomRelationship__c which in Apex we might normally access with MyCustomObject__c.MyCustomRelationship__r

Of course, this isn't a one-off scenario, so we might also have MyCustomObject2__c.MyCustomRelationship2__r, MyCustomObject3__c.MyCustomRelationship3__r, etc. And of course these relationships don't need to be one-to-one or so neatly organized.

But the thing is, we want a generic way to process some of these, so we'd like to make a method with a signature like:

doSomething(SObject sObj, SObjectField sObjectField)

only these aren't actually SObjectFields but rather Schema.ChildRelationships, so in actually we would need a signature like:

doSomething(SObject sObj, Schema.ChildRelationship childRelationship)

But then this still present two problems:

  1. How can I actually get the value for Schema.ChildRelationship from the API name (e.g. MyCustomObject__c.MyCustomRelationship__r)?

  2. Having Schema.ChildRelationship, how I can apply it to my SObject to do something like

    List<SObject> relatedSObjectList = sObj.get(childRelationship)

1 Answer 1


I'll answer your second question first.

To get the child records if you know the relationship name, you pass a String argument to the SObject.getSObjects method:

MyObject__c parent = new MyObject__c();
String relatioonshipName = 'Children__r';
List<Child__c> children = parent.getSObjects(relationshipName);

Now back to your first question. There is no way to get a specific ChildRelationship without looping, but it also doesn't help you if you already have the relationship name as a string. Basically, your loop structure would look like:

ChildRelationship relationship;
for (ChildRelationship relation : SObjectType.MyObject__c.getChildRelationships())
    if (relation.getRelationshipName() = relationshipName)
        relationship = relation;

If you decide you need to do this looping (for example checking permissions, I highly suggest you implement a DescribeCache where you cache these relationships and call a signature like:

public static ChildRelationship getChildRelationship(SObjectType sObjectType, String name)

You must log in to answer this question.

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