You need to sign in to do that
Don't have an account?

How to query the fields of related child objects using dynamic query?
Hi,
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
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()); childList.add(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 +', '; listFields.add(str); } allFields = allFields.removeEnd(', '); query = 'SELECT ' + allFields + ' FROM ' + SobjectApiName + ' where id = \''+apexPages.currentPage().getParameters().get('id')+'\' '; caseList = Database.query(query); } }
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.