You need to sign in to do that
Don't have an account?
Sarah
How to avoid SOQL query inside for loop
I have the below code and there is a SOQL query inside for loop. I have been instructed to avoid SOQL in the loop as these are invoked for every iteration of the loop. Since i am a beginner in Salesforce i don't know how to implement that. Here's my code where i have advised to use Soql query and condition checking before for loop using a map.
if ((isTrgBefore && (isInsert||isUpdate ))){ for( Item eachitem :newItemList ){ if(eachItem.WhoId!=Null){ Schema.SObjectType sobjectType = eachItem.WhoId.getSObjectType(); String sobjectName = sobjectType.getDescribe().getName(); if(sobjectName.equals(UTIL_Constants.SubString)){ List<Strategy> stg=[select Type from Strategy where Id=:eachItem.WhoId]; for(Strategy s:stg){ if(s.Type=='Market Strategy' || s.Type=='Market Potency'){ eachItem.Strategy__c = eachItem.WhoId; } } } } setWhatIds.add(eachItem.WhatId); } }
Can you explain about your requirement?
As per my understanding, Strategy is custom object and you need to link that object to task.
If yes, try with below code.
If this helps, please mark it as best answer.
Thanks!!
Yes I need to link to that object to task
Can we check that "Market Strategy" And "Market Potency" Condition before the for loop.
we need to check the condition with in the for loop.
THanks!!
Please find the working code
Set<Id> whoIdSet = new Set<Id>();
if ((isTrgBefore && (isInsert||isUpdate ))) {
for(Item eachitem : newItemList) {
if(eachItem.WhoId != Null) {
Schema.SObjectType sobjectType = eachItem.WhoId.getSObjectType();
String sobjectName = sobjectType.getDescribe().getName();
if (sobjectName.equals(UTIL_Constants.SubString)) {
whoIdSet.add(eachItem.WhoId);
}
}
}
}
if (whoIdSet.size() > 0) {
List<Strategy__c> strategyList = [SELECT Id, Type FROM Strategy__c WHERE Id IN :whoIdSet AND (Type = 'Market Strategy' OR Type = 'Market Potency')];
if (strategyList.size() > 0) {
for(Strategy__c st : strategyList){
if (st.Strategy__c != st.Id) {
st.Strategy__c = st.Id;
}
}
update strategyList;
}
}
Please mark this as the best answer if it helps
Thanks
Shubham Jain