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??


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

 (SELECT Id,Status,CaseNumber FROM Cases), 
 (SELECT Id,Name FROM Contacts), 
 (SELECT Id,Name FROM Opportunities) 

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


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.