+ Start a Discussion
Jay16Jay16 

Help needed moving SOQL query out of For loop

Hi everyone,

I'm sometimes asked to write code as part of my role, maybe once every 3/4 months. So although I can get by, my code isn't perfect.
I wrote a bunch of triggeres a while back and have just noticed that I left a SOQL query inside a For loop and I can't figure out how to move it out. Could anyone give me some pointers on how I can chieve this please? I'm concerned I will hit governour limits.

Thanks in advance.

Here's the part of the code in question:

trigger setupBonusFields on bc__c (before insert) {
   
        // Create a set of related opps
        set <id> ids = new set <id>();
            for (bc__c newSet : Trigger.new) {
                ids.add(newSet.opportunity__c);
            }

        // Add SA1 & SA2 to map
        map <id,Opportunity> sa1Oppmap= new map<id,Opportunity>();
            for (Opportunity o:[select Sales_Associate_1__c, Sales_Associate_2__c,
                 Sales_Associate_1__r.division__c, Sales_Associate_1__r.region__c, Sales_Associate_2__r.division__c, Sales_Associate_2__r.region__c
                 from opportunity where id in :ids]) {
                sa1Oppmap.put(o.id, o);
            }

Best Answer chosen by Jay16
John PipkinJohn Pipkin
Jay16, 

If you write the SOQL statement when you are declaring the for loop (like you have here), it only runs once. 

All Answers

John PipkinJohn Pipkin
Jay16, 

If you write the SOQL statement when you are declaring the for loop (like you have here), it only runs once. 
This was selected as the best answer
Jay16Jay16
Really? That's handy, maybe there was some method in my work then :) Thanks for clarifying John. Much appreciated.
John PipkinJohn Pipkin
No problem!