I have 3 objects A, B and C. And B and C have lookup to A. I want to find all the objects which have lookup to the object A. I am able to get all the Child Relationships (using schemaMap.get('A').getDescribe().getChildRelationships()) where the object A is having relationship. I need all the objects which have relationship to A object. Please help me how can I all the objects which have relation ship to the selected object. Because I want to set the selected object as a base object and want to create a dynamic SOQL query using fields of the related objects. eg: Select B.name, C.employee From A Where Id = 34852893549. If anyone have any idea please guide me.


Code to create and execute the dynamic SOQL would look something like this:

Id objectAId = ...;
for (ChildRelationship cr : schemaMap.get('A').getDescribe().getChildRelationships()){
    DescribeSObjectResult d = cr.getChildSObject().getDescribe();
    if (d.isQueryable()) {
        Map<String, SObjectField> fs = d.fields.getMap();
        List<String> fieldNames = new List<String>(fs.keySet());
        String soql = ''
                + ' select ' + String.join(fieldNames, ',')
                + ' from ' + String.valueOf(cr.getChildSObject())
                + ' where ' + String.valueOf(cr.getField()) + ' = :objectAId';
        List<SObject> children = Database.query(soql);
        // Do something with the results

Useful references: ChildRelationship Instance Methods and Using Field Tokens.

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.