[SalesForce] How to Query all opportunities ids from account

I write a sample query to fetch account Ids from cases of a particular record type.Then i wrote another sample query parent to child relationship to fetch opportunity ids from accounts.

My sample code

List<Case> c=new List<Case>();
c=[Select Id,accountId from case where RecordTypeId = '01290000000sF3L'];
List<Id> accountIds= new List<Id>();
List<Account> accounts=new List<Account>();
List<Opportunity> opps=new List<Opportunity>();
for(Case cl:c) 
{
accountIds.add(cl.accountId);
}
accounts=[Select Id,name,(select Id,name from opportunities) from account       
where Id in:accountIds];
System.debug('Data in accounts '+accounts);

But my issue is how to get opportunity id from above Soql accounts means how to add those opportunity id's to the list.

for(Account ao:accounts) {
//How to fetch Opportunity ids from above account list.
}

Best Answer

Most efficient:

Set<Id> childIds = new Map<Id, Opportunity>(ao.Opportunities).keySet();

You can also loop through them:

for (Opportunity child : ao.Opportunities)
{
    // ...
}
Related Topic