I have two Apex methods that accomplish the same thing. I am new to the framework and just want to make sure I am interpreting it correctly.
//Method 1:
for (Account a : trigger.new) {
for (Contact c : [SELECT Id, OtherPhone FROM Contact WHERE AccountId= :a.Id]) {
c.OtherPhone= a.Phone; update c; } }
//Method 2:
for (Account a :trigger.new){
acctMap.put(a.Id, a);
}
for (Contact c : [SELECT Id, OtherPhone, AccountId FROM Contact WHERE
AccountIdIN :acctMap.keySet()]){
c.OtherPhone = acctMap.get(c.AccountId).Phone;
contactsToUpdate.add(c);
}
update contactsToUpdate;
My assumption is that both methods look at every Account being triggered, and append the account phone number to each Contact.OtherPhone variable under each account. Method 1 does this with an individual update to every contact and method 2 updates all affected contacts at once by pushing them into a hashmap.
Is this essentially correct? Clarification of anything I'm getting wrong would be much appreciated. Thanks!
You are basically right, both are doing pretty much the same thing, but I would not use neither.
Long story short, Method 1 is not bulky, Method 2 is.
For more details I'd say that
In method 1 there are some possible issues (depending also on the rest of the code)
In method 2 there are also some small issues
Both are fetching in the query OtherPhone, but OtherPhone is going to be overridden, so unless you want to do some other logic with it, there is no need to fetch it in the soql query (If the code in the org is complicated, every byte saved from the heap-size helps).
Either way, this functionality can even be accomplished without code using process builder ;)
I hope its helpful.