You need to sign in to do that
Don't have an account?

Too Many SOQL (Checking OpportunityLineItem)
Hi guys ! i am going through every opportunity to copy records from another object Here is my code
This gives too many soql error because i am checking if there are opportunitylineitems in opportunity in a loop is there a way to do this without querying in a loop any help would be appreciated
List<OpportunityLineItem> result = new List<OpportunityLineItem>(); List<PricebookEntry> pbe = [SELECT Id, Product2Id, IsActive FROM PricebookEntry WHERE Product2Id IN :ProductIds]; for (Opportunity op : opps){ List<OpportunityLineItem> oli = [SELECT OpportunityId FROM OpportunityLineItem WHERE OpportunityId =: op.Id]; if(oli.size() == 0){ for(Sales_Order__c s :so){ for(PricebookEntry pbee : pbe){ for(SalesLine__c SL : productIdToSLineMap.get(pbee.Product2Id)){ if(op.Id == s.Quote__c && SL.Sales_Order__c == s.Id){ result.add (new OpportunityLineItem( OpportunityId = SL.Opportunity_Id__c, PricebookEntryId = pbee.Id, Quantity = SL.Quantity__c > 0 ? SL.Quantity__c : 1, UnitPrice =(SL.Quantity__c > 0 ? (SL.Amount__c > 0 ? SL.Amount__c/SL.Quantity__c : 0) : (SL.Amount__c > 0 ? SL.Amount__c : 0)))) ; } } } } }else{ system.debug('OpportunityLineItem Exists'); } } insert result;
This gives too many soql error because i am checking if there are opportunitylineitems in opportunity in a loop is there a way to do this without querying in a loop any help would be appreciated
Map<Id,List<OpportunityLineItem>> opp2opplineitems = [SELECT ID,NAME,(SELECT Id,OpportunityId FROM OpportunityLineItems) FROM OPPORTUNITY];
Then in loop, you can get opportunitylineitem list by opp2opplineitmes.get(opp.id);
All Answers
Then, you'll likely need to refactor your logic a bit to conicide with "bulkifying" your class too.
Map<Id,List<OpportunityLineItem>> opp2opplineitems = [SELECT ID,NAME,(SELECT Id,OpportunityId FROM OpportunityLineItems) FROM OPPORTUNITY];
Then in loop, you can get opportunitylineitem list by opp2opplineitmes.get(opp.id);