I am facing CPU Run time exception while update opportunity through Data Loader. Because of my rollup trigger. How to avoid for loop inside a for loop?
Trigger:
trigger BudgetAllocationRollup on Budget_Allocation__c (after delete, after insert, after update) {
Set<Id> Opportunityids=new Set<Id>();
Map<id,Opportunity__c> mapOpportunity=new Map<id,Opportunity__c>();
Map<id,List<Budget_Allocation__c>> mapBudget=new Map<id,List<Budget_Allocation__c>>();
if(Trigger.isInsert || Trigger.isUpdate){
List<Budget_Allocation__c> lstBudget=[select id,name,Budget__c,Opportunity1__c ,Opportunity_Flag__c from Budget_Allocation__c where id in:Trigger.newMap.keyset()];
for(Budget_Allocation__c budget:lstBudget){
Opportunityids.add(budget.Opportunity1__c );
}
List<Opportunity__c> opplst=[select id,name,Budget_Allocation_Total__c,(select Opportunity1__c ,id,Budget__c,name,Opportunity_Flag__c from Budget_Allocations__r) from Opportunity__c where id in:Opportunityids];
for(Opportunity__c opp:opplst){
mapOpportunity.put(opp.id,opp);
mapBudget.put(opp.id,opp.Budget_Allocations__r);
}
AggregateResult i=[select sum(Budget__c) from Budget_Allocation__c where Opportunity1__c in:mapOpportunity.keyset()];
for(Id id:mapOpportunity.keyset()){
mapOpportunity.get(id).Budget_Allocation_Total__c=0;
decimal total=0;
for(Budget_Allocation__c budget: mapBudget.get(id)) {
if(budget.Budget__c!=null && budget.Opportunity_Flag__c==true)
mapOpportunity.get(id).Budget_Allocation_Total__c=mapOpportunity.get(id).Budget_Allocation_Total__c+budget.Budget__c;
}
}
if(mapOpportunity!=null && mapOpportunity.size()>0){
try{
update mapOpportunity.values();
}
catch(Exception e){
}
}
}
if(Trigger.isDelete){
List<Budget_Allocation__c> lstBudget=[select id,name,Budget__c,Opportunity1__c ,Opportunity_Flag__c from Budget_Allocation__c where id in:Trigger.oldMap.keyset()];
//system.debug('--lstBudget--->'+lstBudget);
if(lstBudget!=null){
for(Budget_Allocation__c budget:lstBudget){
Opportunityids.add(budget.Opportunity1__c );
}
}
List<Opportunity__c> opplst=[select id,name,Budget_Allocation_Total__c,(select Opportunity1__c ,id,Budget__c,name from Budget_Allocations__r) from Opportunity__c where id not in:Opportunityids];
for(Opportunity__c opp:opplst){
mapOpportunity.put(opp.id,opp);
mapBudget.put(opp.id,opp.Budget_Allocations__r);
}
AggregateResult i=[select sum(Budget__c) from Budget_Allocation__c where Opportunity1__c in:mapOpportunity.keyset()];
for(Id id:mapOpportunity.keyset()){
mapOpportunity.get(id).Budget_Allocation_Total__c=0;
decimal total=0;
for(Budget_Allocation__c budget: mapBudget.get(id)) {
if(budget.Budget__c!=null)
mapOpportunity.get(id).Budget_Allocation_Total__c=mapOpportunity.get(id).Budget_Allocation_Total__c+budget.Budget__c;
}
}
if(mapOpportunity!=null && mapOpportunity.size()>0){
try{
update mapOpportunity.values();
}
catch(Exception e){
}
}
}
}