[SalesForce] How to get Cases, Opportunities, Contacts Associated with Account Object Dynamically

I need to get all the associated Contacts,Opportunities and Cases, for a given Account, if there are any.

Right now, I am doing something like below:

public List<Case> getCases(SObject sobj){
    List<Case> casesList = [SELECT (SELECT Id,Status,CaseNumber FROM Cases) FROM Account WHERE Id=:(String)sobj.get('Id')].Cases;
    return casesList;
}

public List<Case> getContacts(SObject sobj){
    List<Contact> contactsList = [SELECT Id,(SELECT Id,Name FROM Contacts) FROM Account WHERE Id=:(String)sobj.get('Id')].Contacts;
    return contactsList;
}

public List<Case> getOpportunities(SObject sobj){
    List<Opportunity> opportunitiesList = [SELECT Id,(SELECT Id,Name FROM Opportunities) FROM Account WHERE Id=:(String)sobj.get('Id')].Opportunities;
    return opportunitiesList;
}

Is there any better and efficient way to achieve this using dynamic apex??

Can somebody give directions on how to tackle this?

I am guessing this can be simplified alot using dynamic apex but I am not sure on where to start.. Any clues??

Best Answer

I think Dynamic apex will not help in this case. May be you can try query like this.

SELECT id, 
 (SELECT Id,Status,CaseNumber FROM Cases), 
 (SELECT Id,Name FROM Contacts), 
 (SELECT Id,Name FROM Opportunities) 
FROM Account WHERE Id='XXXX'

So you will save on number of SOQL. you should check the performance of this query with read data.

Related Topic