[SalesForce] Want to fetch the child relationship name from the Lookup field name

I am developing a functionality where I am to check for the presence of Child records, before executing a part of code. I can't do hardcoding since my code is going to be a part of a managed package, and object names may differ in the destination orgs.

I have child object's name and the lookup field stored in a custom setting, and I am thinking about storing the child relationship name to be stored in custom setting as well, which will be more helpful in fetching child's list size from Parent records query, rather than replacing '__c with 's__r' all the time, which may cause an issue in case the relationship name is different.

Is there any way using which we can fetch Child relationship name from the lookup field itself?

Here is the code I have tried so far…

for(Lead objLeadRec : lstLead) {
    //LC_Setup_Map_Related_List__c is the custom setting storing the details of the lookup fields with my Lead objects
    for(LC_Setup_Map_Related_List__c objRelatedList1 : lstRelatedListRecords){
        //relatedChildObjName is to get the child objects record count
        relatedChildObjName = objRelatedList1.tdc_tlc__Child_Object__c.replace('__c','s__r');
        System.debug('relatedChildObjName'+relatedChildObjName);
        //System.debug('objLeadRec.get(relatedChildObjName)'+objLeadRec.get(relatedChildObjName));
        if(objLeadRec.getSobjects(relatedChildObjName) != null && objLeadRec.getSobjects(relatedChildObjName).size()!=0){
            //hasRelatedListRecords is the boolean variable on the basis of which some part of code is to be executed
            hasRelatedListRecords = true;
        }
    }
}

Best Answer

No, you need to loop through the parent describe.

for (ChildRelationship relation : SObjectType.Lead.getChildRelationships())
    if (relation.getField() == MyObject__c.MyLookup__c)
        String relationshipName = relation.getRelationshipName();

You should do this processing before you enter your loop, not each iteration.