How to perform Soql query outside for loop?
Here is one approach.
- First get a set of the products you're going to need
- Get all the PBEntry records at once and put them on a map (key = the product name) so you can retrieve them easily later
- In your loop, check for the existence of records with that product name and, if they do, then retrieve the records and iterate to perform your logic
Sample Code
//Create a Set with all the Products
Set<String> productNames = new set<String>();
for(Pricing__c prices: priceList) {
productNames.add(prices.Name__c);
}
//Put the set in a map for easy access
Map<String, List<PricebookEntry>> PBMap = new Map<String, PricebookEntry>();
for (PricebookEntry pb : [SELECT Id, IsActive, CurrencyIsoCode FROM PricebookEntry
WHERE Product2.Name in :productNames]) {
if (! PBMap.containsKey(pb.Product2.Name)) {
PBMap.put(pb.Product2.Name, new List<PricebookEntry>);
}
List<PricebookEntry> pbList = PBMap.get(pb.Product2.Name);
pbList.add(pb);
PBMap.put(pb.Product2.Name, pbList);
}
for(Pricing__c prices: priceList) {
If (PBMap.containsKey(prices.Name__c)){
//Get all the PB Entries that matched
List<PricebookEntry> pbList = PBMap.get(prices.Name__c);
for(Pricebookentry PB: PBList){
OpportunityLineItem OpItem=new OpportunityLineItem();
oli.PriceBookEntryId=PB.Id;
oli.Opportunityid=prices.Opportunity__r.id;
oplineList.add(oli);
}
}
insert oplineList;