3

I'm working on building a new trigger that for some reason has me a bit stumped on the best way to query some related data.

I have an array of recently updated opportunities:

public void OnAfterUpdate(Opportunity[] updatedOpportunities) {
    //How do I build a Map of related opportunity line items?
    //lineItems = someMap.get(someOpportunityId);
}

In order to avoid hitting any governor limits I'd like to get all of the related opportunity line items, but, in a way that they are easily retrieved based on the opportunity id.

I was originally thinking of doing something like:

opportunityLineItemsMap = new Map<Id, List<OpportunityLineItem>>([SELECT OpportunityId, PricebookEntry.Product2.Name FROM OpportunityLineItem]);

However, this obviously isn't valid syntax. Is there an easy way to build a map like this or am I stuck with a nested loop of iterating over each opportunity and then over each line item to build the data structure myself?

4

You should be able to do something like this:

List<Opportunity> opptys = [SELECT Id, Name, (SELECT Id, PricebookEntry.Product2.Name FROM OpportunityLineItems) FROM Opportunity WHERE Id =: updatedOpportunities];

Then you can reference the list of OpportunityLineItems with something like the following to iterate over each Opportunity and create a map:

Map<String, List<OpportunityLineItem>> opportunityLineItemsMap = new Map<String, List<OpportunityLineItem>>();
for (Opportunity oppty : [SELECT Id, Name, (SELECT Id, PricebookEntry.Product2.Name FROM OpportunityLineItems) FROM Opportunity WHERE Id =: updatedOpportunities])
{
  opportunityLineItemsMap.put(oppty.Id, oppty.OpportunityLineItems);
}

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.