+ Start a Discussion
dnvansantdnvansant 

Too many SOQL queries

I think the issue is the SOQL in the for statement, but I'm having issues trying to put this kind of SOQL Count in a map. I'm assuming some sort of mapping is required to get around my too many queries issue.

 

Can someone please point me in the right direction?

 

 

trigger StarRatingCampaign on CampaignMember (after insert)
{
Set<Id> leadId = new Set<Id>();

for (CampaignMember cm : trigger.new){leadId.add(cm.CampaignId);

Integer i = [SELECT count() FROM CampaignMember where CampaignId != '701C0000000ZFdA' and CampaignId=:Leadid and (Star_RatingF__c = '5' OR Star_RatingF__c = '4')];

Campaign newCampaign = new Campaign(id=cm.campaignid, Total_5_4_Star_Leads__c = i );
update newCampaign;}
}

Reppin__505Reppin__505

I was kinda working on that today. I attempted to make an aggregate query map that passes the id of an object as a map key, and the count as the map value. I wasn't able to get it to work however. 

 

So i decided to create a regular map, and accumulate the total of iterations of that map to get the count.

 

Pseudo Example:

 

trigger Contact(before insert)
{
Map<Id, List<Account>> mapAccounts();

for(Accounts a : [Select Accounts] )
{
mapAccounts.put(Id, a)
}

Integer count = 0;

for(Contact c : mapAccounts.get(thisContact.AccountId))
{
count++;
}
}

 

 

Hope this helps.

dnvansantdnvansant

This seems to work, thanks for your help!

trigger StarRatingCampaign on CampaignMember (after insert){
Set<Id> CampaignMemberID = new Set<Id>();

Set<Id> CampaignID = new Set<Id>();
for (CampaignMember cm : trigger.new){CampaignID.add(cm.CampaignId);}

Map<Id, set<ID>> mapCampaignMembers=new Map<id,set<ID>>();

for(CampaignMember cmm : [SELECT id FROM CampaignMember where CampaignId != '701C0000000ZFdA' and CampaignId=:Campaignid and (Star_RatingF__c = '5' OR Star_RatingF__c = '4')] )
{
CampaignMemberID.add(cmm.id);
mapCampaignMembers.put(cmm.Id, CampaignMemberID);
}

for (CampaignMember cm : trigger.new){
CampaignID.add(cm.CampaignId);

If(mapCampaignMembers.get(cm.Id)!=null){
Set<id> counts = mapCampaignMembers.get(cm.Id);
Integer i = counts.size();
Campaign newCampaign = new Campaign(id=cm.campaignid, Total_5_4_Star_Leads__c = i );
update newCampaign;
}else{}}}

 

rgdcrgdc

This is a greate Site:

 

http://th3silverlining.com/2009/07/01/how-to-avoid-avoid-governor-limits-part-1-of-n/

 

It help me a lot.

 

 

regards[]