I am creating a trigger on Opportunity, whenever new Opportunity is inserted the value of Amount field get summed up for all other Opportunity of the same parent Account and display the sum on the Account object in the custom field Total_Amount__c. I have created
trigger sumOpportunity on Opportunity (after insert) {
list<Opportunity> newOpportunity = trigger.new;
Set<Id> parentAccId = new Set<Id>();
for(Opportunity opp : newOpportunity){
parentAccId.add(opp.AccountId);
}
List<account> parentAcc = [Select Total_Amount__c ,(Select Amount from Opportunities) from Account where Id in :parentAccId];
for(Account acc : parentAcc){
decimal totalAmt = 0;
for(Opportunity opp : acc.Opportunities){
totalAmt += opp.Amount;
}
acc.Total_Amount__c = totalAmt;
}
if(parentAcc.size() > 0){
update parentAcc;
}
}
so is there a way that we can use aggregate function to sum the amount on opportunity so that we don't have to use nested loop (first iterating over account then on opportunity).