How to get relation name programatically

You could use the SObject's getDescribe method (from the parent object), then call the DescribeSObjectResult's getChildRelationships() method. This will give you a list of Schema.ChildRelationship entries, each one providing the name (getRelationshipName) you'd use to query with, and the field (getField) that is the lookup field on the child object (it's an SObjectField, so you may need to run a describe on it if you need more information.


SObjectField parentField;
for(ChildRelationship rel: Patient__c.SObjectType.getDescribe().getChildRelationships()) {
    if(rel.getSObjectType() == Inquiry__c.SObjectType) {
        parentField = rel.getField();
        break;
    }
}
// Here, parentField is the Inquiry__c's lookup field to Patient__c

You can use the describe for Patient__c to get the child relationships, and loop through them until you find the one for Inquiry__c and get the field name from that like so:

for(Schema.ChildRelationship relation : sObjectType.Patient__c.getChildRelationships()){
    if(relation.getChildSObject() == Inquiry__c.sObjectType ){
        FieldTokenYouWant = relation.getField();
    }
}

Here is one way to do that starting from the child side using the Contact object as an example:

SObjectType t = Contact.SObjectType;
for (SObjectField f : t.getDescribe().fields.getMap().values()) {
    if (f.getDescribe().getType() == DisplayType.Reference) {
        System.debug(f + ' is a lookup');
    }
}

See the DescribeFieldResult documentation for more detail on the field information that is available.

If you know the parent object (as you appear to) sfdcfox's approach is better.

(Incidentlly this describe API feels a bit strange in this area in that you declare the dependency at the child side but the parent-side has the more convenient API i.e. there is no getParentRelationships method.)

Tags:

Apex