1

I am currently doing trailhead and in one exercise I saw the following SOQL and I am trying to get an understanding of it.

Map<Id,Account> acctsWithOpps = new Map<Id,Account>([SELECT Id,(SELECT Id FROM Opportunities) FROM Account]);
System.debug(acctsWithOpps);

The above snippet produces the following output

enter image description here

Basically it displays all the opportunities (if there are any) for an Account.

My question is with respect to the map intialization.

In the map init statement, I do not see any Opportunity object at all.

All it says is Map<Id, Account> where are the Opportunity objects here ?

4

It is called a Left Outer Join. You are getting your Opportunity records in the sub-query:

(SELECT Id FROM Opportunities)

So each Account has a List<Opportunity> which you can iterate.

for (Account account : [select (SELECT Id FROM Opportunities) FROM Account])
{
    List<Opportunity> childOpportunities = account.Opportunities;
}
0

Basically using this, we can get child objects. You can fetch Opportunities using fetched accounts. See example below

Map<Id,Account> acctsWithOpps = new Map<Id,Account>([SELECT Id,(SELECT Id FROM Opportunities) FROM Account]);
        System.debug(acctsWithOpps);

for (Account account : acctsWithOpps.values())
{
    List<Opportunity> childOpportunities = account.Opportunities;
    System.debug(childOpportunities);
}

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.