+ Start a Discussion
Akanksha Gupta 58Akanksha Gupta 58 

How to query the fields of related child objects using dynamic query?

I have a requirement where I need to query all the fields of Case object along with all the fields of the Child objects of Case. How do I built a query for the same. Right now I am able to query only the fields of Case object. I am not sure how to design an inner query using dynamic apex.
This is my code snippet
public class TEL_CaseController
    public List<Case> caseList{get;set;}
    public List<SObjectType> childList{get;set;}	
    public String query{get;set;}
    public List<String> listFields{get;set;}
    String allFields = '';
    public TEL_CaseController ()
        String SobjectApiName = 'Case';
        childList = new List<SObjectType>();
        Schema.SObjectType convertType = Schema.getGlobalDescribe().get(SobjectApiName);
        Schema.DescribeSObjectResult obj = convertType.getDescribe();
        for (Schema.ChildRelationship cr: obj.getChildRelationships()) 
            system.debug('Child Object Name:'+cr.getChildSObject());
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
        Set<string> mapset = fieldMap.keyset();
        caseList = new List<Case>();
        listFields = new List<String>();
        FOR ( String str:mapset )
            allFields += str +', '; 
        allFields = allFields.removeEnd(', ');
        query = 'SELECT ' + allFields + ' FROM ' + SobjectApiName + ' where id = \''+apexPages.currentPage().getParameters().get('id')+'\' ';
        caseList = Database.query(query);

let's say one of the childs of Case is CaseChild__c ,that would be something like this :
Select Id, SomeField, (Select Id,SomeField from CaseChild__c) from Case WHERE Id = :myId

Akanksha Gupta 58Akanksha Gupta 58
@bretondev I want all the fields in child as well,not just one
Ravi Dutt SharmaRavi Dutt Sharma
Hope this helps:
Schema.DescribeSObjectResult result = Case.SObjectType.getDescribe();
for (Schema.ChildRelationship cr: result.getChildRelationships()) 
  system.debug('====child object==='+cr.getChildSObject());

Once you have the child object name, you can reuse your same code to get all the fields and construct a SOQL. Please mark this as the best answer if it resolves your problem. Thanks.
Akanksha Gupta 58Akanksha Gupta 58
Hey @Ravi I got the list of child objects. I have issues with constructing the query. Can you help me with the same?