+ Start a Discussion
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com 

Get soql outside for loop in Apex.Please help!!!!

Hi,

   I ahve two objects Opportunity and Attcahment_c, One opportunity can have multiple atachments. I ahve wrtiien this login on them:

for(Opportunity opp: Trigger.new)
       {
         attchmnt=[select id,DownloadedIndicator__c from Attachment__c where (Opportunity__c=: opp.id  AND Source__c='Sales')];
         for(i=0;i< attchmnt.size();i++)
         {
            attchmnt[i].DownloadedIndicator__c=false;
         }
       }
// Updating the list of attchments      
        if(attchmnt.size()!=0)
        {
             update attchmnt;
        }

Need to get soql out of the for loop. Can anyone please help me with this?

Vinit_KumarVinit_Kumar

shrey,

 

Please try below :-

 

List<Id> oppIdList = new List<Id>();

 

for(Opportunity opp: Trigger.new)
{
if(opp.Source__c=='Sales' )
oppIdList.add(opp.id);
}
attchmnt=[select id,DownloadedIndicator__c from Attachment__c where Opportunity__c in: oppIdList];

AlagarAlagar

Shrey,

 

tyr this code..it will work

 

set<Id> oppId = new set<id>();

for(Opportunity opp: Trigger.new){

    oppId.add(opp.id);

}

 

List<Attachment__c> attchmnt = new List<Attachment__c>();

 

for(Attachment__c att : [select id,DownloadedIndicator__c from Attachment__c where Opportunity__c IN: oppId   AND Source__c='Sales']){

    att.DownloadedIndicator__c=false;

    attchmnt.add(att);

}

 

if(attchmnt.size() > 0) {
      update attchmnt;
 }

 

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Thanks a lot Vinit and Alagar for your prompt reply. I have written this piece of code and it seems to work fine.  The code is given below:

 

trigger testtrigger on Parent_Object__c (after update) {
list<Child_Object__c>  colist= new list<Child_Object__c>();
list<Id>  idlist= new list<Id>();
Integer i;
Integer j;

for(Parent_Object__c  po:trigger.new){
  idlist.add(po.id);
}
colist=[select id,Download_Indicator__c from Child_Object__c where (Parent_Object__c IN: idlist  AND Source__c='Sales')];
for(j=0;j<colist.size();j++){
colist[j].Download_Indicator__c=false;
}
 
 if(colist.size()>0){
   update colist;
  }
}

 

Please give your review comments on this.

Vinit_KumarVinit_Kumar

Shrey - This seems fine to me.