2

For Trigger.New in an order trigger, I use the order's accountId field to query for 3 fields on the related account. As follows...

    for(Order o : Trigger.New)
    {
        Id theID = o.AccountId;
        Account thisAccount = [SELECT Household_Total__c, Household_Children__c FROM Account WHERE ID= :theId];

However, this trigger goes off with a process I'm developing called "Mass Order Create", and as you can tell from the name, I'm making a lot of orders at once. So, this one query in Trigger.new for the account with the given Order's accountID field is putting me over governor limits.

Is there any way to get the related account's fields without querying? If not, what might somebody suggest doing instead?

I found this somewhere that gets fields related to Account, but I don't think it's quite pulling information from a specific record, or if so, the person who provided the code left little explanation, so I don't know how to use it if it's there. (o is trigger.New)

        Id theID = o.AccountId;

        Schema.SObjectType token = theID.getSObjectType();
        Schema.DescribeSObjectResult dr = token.getDescribe();
        sObjFieldName = dr.Fields.getMap().keyset();

1 Answer 1

10

Yes, of course. The first step is to gather a collection of the Account ids.

Set<Id> accountIds = new Set<Id>();
for (Order order : trigger.new) accountIds.add(order.AccountId);

The next step is to query the Account records and put them in a Map:

Map<Id, Account> accounts = new Map<Id, Account>([
    SELECT Fields FROM Account WHERE Id IN :accountIds
]);

The last step is to retrieve them in your loop (without an additional query per):

for (Order order : trigger.new)
{
    Account thisAccount = accounts.get(order.AccountId);
    // do other stuff
}
3
  • Note that your trigger is executed in batches of 200 records. If you are inserting 10000 orders at once, this will result in 50 iterations, so 50 queries. Not a problem in this case, but if you have more queries in your trigger you could be in trouble. Commented Nov 16, 2016 at 20:29
  • Isn't that query in the mapping going to give the same issue? Where exactly are you putting Map<Id, Account ... ect? Thank you for your answer! It's very helpful, but I do wonder if it'll do what I want... Commented Nov 16, 2016 at 20:33
  • I understand! Never mind. Trying it now! Commented Nov 16, 2016 at 20:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .