You need to sign in to do that
Don't have an account?

Apex Trigger SOQL Limit problem
I am trying to bulk update Contacts (FAs) with number of leads related to them.
I get stuck because of the SOQL limit... Please help.
thank you.
trigger CountLeads on Contact (before insert, before update) { //production version Map <Id, Contact > FAList = new Map<Id, Contact> ( [SELECT Id, Leads_2010_YTD__c FROM Contact WHERE Id in :Trigger.new] ); Map<Id, Integer> LeadCount = new Map<Id, Integer> (); for (Contact con: Trigger.New ){ Integer i = [SELECT count () FROM Lead WHERE FA__c = :con.Id AND (CreatedDate >= 2010-01-01T00:00:00Z AND CreatedDate <= 2010-12-31T00:00:00Z)]; LeadCount.put (con.Id, i); } //end for con try { for (Contact FAupdate : Trigger.new){ FAupdate.Leads_2010_YTD__c = LeadCount.get(FAupdate.Id); } // end for FAupdate }// end try catch (System.Queryexception e){ System.debug('FA Lead Count ERROR:' + e); } // end catch }
Rather than doing hte count query in a loop, you should be able get all the counts in one go with an aggregate query, by grouping on the FA__c field.
All Answers
Rather than doing hte count query in a loop, you should be able get all the counts in one go with an aggregate query, by grouping on the FA__c field.
Thank you . :)
Here is the end code in case someone has the same trouble.