0

I'm making a trigger that runs when contacts are updated. Part of that trigger is to get a list of accounts (the whole object, not just the ID) associated with the contacts that are being updated.

Initially I was doing a SOQL query in a loop, but this eventually ran into limits when doing imports from the data loader.

List<Account> Accounts = new List<Account>();
for(Contact c: Trigger.new){
    Accounts.add([SELECT ID, Other_Fields FROM Account WHERE ID = c.Account]);
}

Is there a way to get a list of master records when from the detail/child records in trigger.new that is bulk friendly.

0

I'm sure there are plenty of ways to do this, but this is what I got to work. When you start you have Trigger.new which contains all of the records being updated, in this case contacts. The contact has a field for account on it, so the first step is we need to get all of those into a set. I choose set here because then you don't have to worry about duplicate accounts (if your trigger has two Contacts at the same Account).

//Create an empty set
Set<ID> SetAccountID = new Set<ID>();

//Loop through and add Accounts to the list
for(Contact c: Trigger.new){
    SetAccountID.add(c.Account);
}

//Now use that Set in a SOQL Query while making a list
List<Account> Accounts = [SELECT ID, other_fields__c
                          FROM Account
                          WHERE ID
                          IN: SetAccountID];

Also you can use any list in place of trigger.new.

|improve this answer|||||
  • I am just wondering, why you have answered your own question like the very next second of asking? May be valid/invalid/whatever, but WHY? – Arnold Jr. Feb 1 '18 at 20:42
  • In case anyone else has a similar question as me. I'm very new to apex and programming in general so I'm not even sure what the right question to ask is half of the time. So for any future people who are in my shoes and asking questions the same way as me they will have an easier time of it than me. It is actually encouraged per link @ArnoldJr. – denvergreene Feb 1 '18 at 20:51
  • 1
    There's no problem with answering your own question. Just please take a moment to search if it's a duplicate first. – Adrian Larson Feb 1 '18 at 20:55
  • Perhaps it is because I am a beginner and not sure what to search for, but the article you marked this as being a duplicate of did not show up in my search. It uses different language and is higher level than this question. Yes, it has the answer so fine if it is considered a duplicate, but it isn't findable when looking for the specific task. – denvergreene Feb 1 '18 at 21:01
  • Just search [bulkification] and sort by votes. It's the first result. – Adrian Larson Feb 1 '18 at 21:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.