I am trying to create a batch that send an Email anytime that status (Known_Error_Status__c) on a article is changed and the Article is 'Online'
I have enable field history tracking on the object (Knowledge__kav) which gives me access to the History object (KnowledgeArticleVersionHistory)
When querying the KnowledgeArticleVersionHistory with 'Query Editor' I am able to retrieve the data
But when trying to make an inner query, I get an error: Didn't understand relationship 'Histories' in FROM part of query call.
List<Knowledge__kav> kavList = [SELECT KnowledgeArticleId,
(SELECT NewValue, Oldvalue FROM Histories WHERE FieldName = 'Knowledge__kav.Known_Error_Status__c') FROM Knowledge__kav];
Is there a way to query oldValue and newValue in a Batch? So that an email can be sent via the batch anytime the Article has been published and the status has been updated Thanks
here is the batch
global class BatchArticleEmail implements Schedulable, Database.Batchable<SObject> {
global string query;
// To schedule batch
global void execute(SchedulableContext sc) {
Id batchProcessId = Database.executeBatch(this);
}
// Constructor to query articles
global BatchArticleEmail() {
query = 'Select Id, KnowledgeArticleId, Known_Error_Status__c FROM Knowledge__kav WHERE PublishStatus=\'Online\'';
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(Query);
}
global void execute(Database.BatchableContext BC, List<Knowledge__kav> scope) {
System.debug('#### Scope BatchArticleEmail ' + scope.size());
//Check if Status has been updated
Set<Id> kavIds = new Set<Id>();
List<Knowledge__kav> kavList = [SELECT KnowledgeArticleId,
(SELECT NewValue, Oldvalue FROM Histories WHERE FieldName = 'Knowledge__kav.Known_Error_Status__c') FROM Knowledge__kav];
for(Knowledge__kav kv : kavList) {
kavIds.add(kv.KnowledgeArticleId);
}
System.debug('BatchArticleEmail kavList KnowledgeArticleId ' +kavIds);
Map<Id, Known_Error_Subscription__c> kesMap = new Map<Id, Known_Error_Subscription__c>(
[SELECT KnowledgeKA__c FROM Known_Error_Subscription__c WHERE KnowledgeKA__c IN :kavIds]);
System.debug('BatchArticleEmail Known_Error_Subscription__c Map ' +kesMap);
for (Knowledge__kav kav : scope) {
for(Known_Error_Subscription__c kes : kesMap.Values()) {
kes.Last_Known_Error_Status__c = kav.Known_Error_Status__c;
System.debug('***Last_Known_Error_Status__c ' + kes.Last_Known_Error_Status__c);
}
EmailManager.sendEmailToKnownErrorSubscribers(scope);
}
update kesMap.values();
}
global void finish(Database.BatchableContext info) {
}
}