In the following piece of code, i am trying to do a dynamic parent - child query

 public static void fetchRelatedRecords(SObject primaryRecord){

    String recordId = (String)primaryRecord.get('Id');
    Map<String, Schema.SobjectType> keys = new Map<String, Schema.SobjectType>();
    Map<String, Schema.SobjectType> describe = Schema.getGlobalDescribe();
    for(String s : describe.keyset()){

    Schema.SObjectType sobjectTypeObj = keys.get(recordId.substring(0,3));        
    Schema.DescribeSObjectResult obj = sobjectTypeObj.getDescribe();        
    String query = 'select Id, ';
    for (Schema.ChildRelationship cr: obj.getChildRelationships()){
        system.debug('Child Object Relationship Name:'+cr.getChildSObject());
        query = query + '(select Id from ' + String.valueOf(cr.getChildSObject()) + '), ';            
    query = query.removeEnd(', ');
    query = query + ' from ' + String.valueOf(sobjectTypeObj) + ' where Id = ' + '\'' + recordId + '\'';
    List<SObject> relatedRecordList = Database.query(query);

My problem here is that, the line

system.debug('Child Object Relationship Name:'+cr.getChildSObject());

gives the child object Name, but what I want is the Relationship Name.

e.g. If Account is the parent of Custom object Author, i want the Name Author__r and not Author__c.

Is there any way to achieve that?

I tried using cr.getRelationshipName() as well, but that did not work either.

1 Answer 1


You need : getRelationshipName() in this part of code (it may not worked for you, because you haven't checked it for null value):

for (Schema.ChildRelationship cr: obj.getChildRelationships()) {
    if (cr.getRelationshipName() == null) continue;
    system.debug('Child Object Relationship Name:'+cr.getRelationshipName());
    query = query + '(select Id from ' + String.valueOf(cr.getRelationshipName()) + '), ';            

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.