0

I have an account record that I want to get every single possible child record - ideally as a list of IDs.

Currently I am doing the following:

for(Opportunity opp : [SELECT ID From Opportunity WHERE AccountId =: accountId])
{
        idList.add(opp.Id);
}
// same for case
// same for customobject1 
// etc...

Is there a way I can do this efficiently and easily?

I had an idea to do something like:

Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
// for each child object
// get parent relationship to account name
// build dynamic query
// database.execute('superlongquery');
// build list of ID from above query

Is this the best approach?

0

You can make use of DescribeSObjectResult which will give you all the ChildRelationships, then loop through the ChildRelationships and build a dynamic query and collect all the Ids in a common List or Set.

Id accountId ='';//your accountid
Set<Id> idList = new Set<Id>();
DescribeSObjectResult describeResult = Account.SObjectType.getDescribe();
for (ChildRelationship childRelation : describeResult.getChildRelationships()) {
    if(childRelation.getChildSObject().getDescribe().isQueryable()){
        SObject[] sobjectRecords = Database.query('select Id from ' + childRelation.getChildSObject() + ' where ' + childRelation.getField() + ' = :accountId');
        for (SObject sobj : sobjectRecords) {
            idList.add(Id(sobj.get('Id')));
        }
    }
}

You can get further information on ChildRelationship on this link.

  • Thanks. That's exactly what I needed. I had to add a check inside the loop to ensure the child object was queryable but it works perfectly. if(childRelation.getChildSObject().getDescribe().isQueryable()) – scousins Jun 13 at 10:12
  • That's great !! Updated the answer with queryable check – Vijay Ganji Jun 13 at 10:32

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.