Object access from SOQL results

I was reading Dan Appleman’s 2nd edition on Advanced Apex Programming and looking at the code samples. In one sample, Dan showed me something I didn’t know you could do in Apex – something that had eluded me in 6 years – and so basic. I was so chagrined but, with shame, comes resolution to help others avoid the same fate.

Let’s look a typical SOQL on Opportunity that references both parent and child objects:

    Opportunity o = [select account.id, account.name,
                            id, name,
                            (select id, quantity
                              from OpportunityLineItems)
                      from Opportunity where id = :someId];

Well, we know we can reference the child objects easily with:

   List<OpportunityLineItem> oliList = o.opportunityLineItems;

But here is what I did not know – you can also reference the Account object as well

   Account a = o.account;  //sheesh

This is handy if you need to update the lookup object. Thus you avoid unnecessary SOQL to fetch it.

Leave a Reply

Your email address will not be published. Required fields are marked *