I know that the reason for this it's because I have a query that it's executed inside a loop, but I don't see how to redesign the code to avoid this. Any help will be appreciated.
Basically, I have a scheduled class that queries cases with certain criteria and checks if they have a public article attached, if the article is public, then an email should be sent to the case contact.
This is part of my scheduled class code.
public void sendKBArticle(){
Boolean hasPublicArticles;
Id EmailTemplateId='00XP0000000MHPI';
Map<id,case> cMap = new Map<id,case>(
[Select Id,ContactId from Case Where Owner.Type='User' AND IsClosed=false AND KB_Article_Sent__c=false
AND Status NOT IN ('Pending Bug Fix','Solution Provided','Escalated','Reopened')
AND RecordType.Name IN ('Internal', 'Customer Portal') AND CreatedDate = LAST_N_DAYS:3 ]);
if(!cMap.IsEmpty()){
for(Case cnt : cMap.values()) {
ArticlePublicLinksonEmail cpkb=new ArticlePublicLinksonEmail();
hasPublicArticles=cpkb.getPublicArticles(cnt.id);
if(hasPublicArticles){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId(EmailTemplateId);
mail.setTargetObjectId(cnt.ContactId);
mail.setWhatId(cnt.Id);
mail.setSaveAsActivity(true);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
Cnt.KB_Article_Sent__c=true;
}
}
try {
update cMap.values();
} catch (DMLException e){
.....some code
}
}
}
}
As you can see, inside the loop I am passing the object id to another method, this method uses this case id to query if the case has a public article attached. Therefore, if I have many cases I hit the query limit.
Any ideas how to fix this or any suggestions in how to approach this in a different way?
Thanks!