I am currently in the process of bulkifying some trigger code. On a high level, I receive a list of Contact
objects, then I need to find the Account
associated with it, and count the number of primary contacts that Account
has.
This was the original implementation:
public class ContactTriggerHelper {
public static void AllocatePrimaryContactOnInsert(List<Contact> contacts) {
List<Account> accountsToUpdate = new List<Account>();
for(Contact contact: contacts) {
if(contact.AccountId != null) {
Account account = [select Id from Account where Id = :contact.AccountId];
integer count1 = [ select count() from Contact where Primary__c = true and AccountId = :contact.accountId ];
integer count2 = [ select count() from AccountContactRole where IsPrimary = true and AccountContactRole.AccountId = :contact.accountid ];
if(count1 + count2 == 0) {
//Do some stuff to the account
accountsToUpdate.add(account);
}
}
}
update accountsToUpdate;
}
}
Obviously, this runs into governor limits very quickly, so I'm trying to bulkify the queries by getting everything into one query. This is how far I've gotten so far:
public static void AllocatePrimaryContactOnInsert(List<Contact> contacts, Map<Id,Contact> newMap) {
List<Contact> contactInfo = [select Id,
(select Id from Account),
(select count() from Contact where Primary__c = true) count1,
(select count() from AccountContactRole where IsPrimary = true) count2
from Contact
where Id in :newMap.keySet()
];
...
}
Unfortunately, I'm running into a roadblock here where I don't know the next step. I don't even know if I'm getting the account correctly, and how do I get the counts from the Contact
and AccountContactRole
tables properly? I would have naively assumed that I would need to have something like (select count() from Contact where Primary__c = true and AccountId = :acc.Id)
but I don't have access to the account's Id from the subquery.
Thank you!