You need to sign in to do that
Don't have an account?
Sangeeta10
Need help getting Soql outside for loop
I have a custom object Referral__c which has a lookup to Account and Oppty. Usecase is whenever a new oppty is created and Account on that oppty has a Referral, attach oppty to the Referral as well. My below code works perfectly fine, but would like to know how can I get Soql outside for loop.
public void AddOpptytoReferral(List<Opportunity> newOpps)
{
List<Referral__c> RPtoupdate=new list<Referral__c>();
for(Opportunity Opp: newOpps)
{
if(Opp.RecordTypeid=='012j0000000z1iCAAQ' || Opp.RecordTypeid=='012j0000000z1lBAAQ')
{
List<Referral__c> RP=new list<Referral__c>([select id,Opportunity__c from Referral__c where Referral_Account__c= :Opp.AccountId and Expiration_date__c>= today and Opportunity__c=null and Referral_Type__c='Customer Referral' order by createdDate asc limit 1]);
if(RP.size() > 0)
{
RP[0].Opportunity__c=Opp.Id;
RPtoupdate.add(RP[0]);
}
}
}
if(RPtoupdate.size()>0){
update RPtoupdate;}
}
public void AddOpptytoReferral(List<Opportunity> newOpps)
{
List<Referral__c> RPtoupdate=new list<Referral__c>();
for(Opportunity Opp: newOpps)
{
if(Opp.RecordTypeid=='012j0000000z1iCAAQ' || Opp.RecordTypeid=='012j0000000z1lBAAQ')
{
List<Referral__c> RP=new list<Referral__c>([select id,Opportunity__c from Referral__c where Referral_Account__c= :Opp.AccountId and Expiration_date__c>= today and Opportunity__c=null and Referral_Type__c='Customer Referral' order by createdDate asc limit 1]);
if(RP.size() > 0)
{
RP[0].Opportunity__c=Opp.Id;
RPtoupdate.add(RP[0]);
}
}
}
if(RPtoupdate.size()>0){
update RPtoupdate;}
}
Let us know if this will help you
Try the code below :-
In the above code what am trying to do is am storing the AccountId of Referral__c as keyset with the list of Referral__c as the value. And I can fetch the records of Referral__c inside the for each loop without Soql Query.
Regards
Akshay
Please mark my answer as a solution if it was helpful