trigger trgRollUpToAccount on Investment__c (after insert, after update) { //List to store Account IDs List AccountIDs = new List(); //Get list of target accounts from investment__c for(Investment__c i: Trigger.new) { AccountIDs.add(i.Target_Company__c); } //query to get all investment records whose account IDs are in the list AggregateResult[] groupedResults = [Select count(id)DealCount, Target_Company__c from Investment__c where Target_Company__c in :AccountIDs Group by Target_Company__c];
// get group of account objects to update Map<id,Account> accountMap = new Map<id,Account>([Select id, DealCount__c from Account where id in :AccountIds]);
//iterate over grouped results and set the account map's data to match
**for(AggregateResult ar: groupedResults) {
trigger trgRollUpToAccount on Investment__c (after insert, after update)
{
//List to store Account IDs
List<Id> AccountIDs = new List<Id>();
//Get list of target accounts from investment__c
for(Investment__c i: Trigger.new)
{
AccountIDs.add(i.Target_Company__c);
}
//query to get all investment records whose account IDs are in the list
AggregateResult[] groupedResults = [Select count(id)DealCount, Target_Company__c from Investment__c
where Target_Company__c in :AccountIDs Group by Target_Company__c];
// get group of account objects to update
Map<id,Account> accountMap = new Map<id,Account>([Select id, DealCount__c from Account where id in :AccountIds]);
//iterate over grouped results and set the account map's data to match
**for(AggregateResult ar: groupedResults)
{
accountMap.get(ar.get('Target_Company__c' )).DealCount__c = ar.get('DealCount');
}**
//Update account objects:
try {
update accountMap.values();
}
catch(DmlException e) {
System.debug(e.getMessage());
}
}
}**
//Update account objects: try { update accountMap.values(); } catch(DmlException e) { System.debug(e.getMessage()); }
}