I am getting an error: 'System.LimitException: Too many SOQL queries: 101' when I run a testing class for another class similar to this one, which is located in the same Object. I am trying to use classes that handle all the code instead of writing the code in triggers. Can anybody please tell if the code i wrote for this class is good approach or should I use a different one.
I will appreciate any help!
Trigger code:
trigger RollupSalesAndUnits on MWSOrderItem__c (before update) {
//to fire the class rollupSalesTriger
if (Trigger.isUpdate) {
RollupSalesAndUnits.Run(Trigger.new);
}
}
Class code:
public class RollupSalesAndUnits {
public static void Run(MWSOrderItem__c [] items){
Map<Id, NRProducts__c > osos = new Map<Id, NRProducts__c >();
for(MWSOrderItem__c p : items){
if(!String.isEmpty(p.NRProduct__c )){
NRProducts__c prod = osos.get(p.NRProduct__c );
if (prod == null) {
prod= new NRProducts__c (Id = p.NRProduct__c );
osos.put(p.NRProduct__c , prod);
}
for(AggregateResult result : [SELECT NRProduct__c p, SUM(Detail_Total__c) FROM MWSOrderItem__c WHERE NRProduct__c =: p.NRProduct__c AND AgeSet__c < 7 AND Order_Complete__c = 'Yes' GROUP BY NRProduct__c]){
prod.X24_Hrs_Sales__c = (Double)result.get('expr0');
}
for(AggregateResult result : [SELECT NRProduct__c p, SUM(Detail_Total__c) FROM MWSOrderItem__c WHERE NRProduct__c =: p.NRProduct__c AND AgeSet__c < 7 GROUP BY NRProduct__c]){
prod.X7_Days_Sales__c = (double)result.get('expr0');
}
for(AggregateResult result : [SELECT NRProduct__c p, SUM(Detail_Total__c) FROM MWSOrderItem__c WHERE NRProduct__c =: p.NRProduct__c AND AgeSet__c < 30 GROUP BY NRProduct__c]){
prod.X30_Day_Sales__c = (double)result.get('expr0');
}
for(AggregateResult result : [SELECT NRProduct__c p, SUM(Detail_Total__c) FROM MWSOrderItem__c WHERE NRProduct__c =: p.NRProduct__c AND AgeSet__c < 60 GROUP BY NRProduct__c]){
prod.X60_Days_Sales__c = (double)result.get('expr0');
}
}
}
update osos.values();
}
}