0

I have a situation, where I need to delete both parent and child log files. I need a batch file, as the number of records is large, and the delete is on a weekly basis.

OFC - I can write a second apex batch, and execute it, but I prefer not to.

I am able to write the code to delete the child records with ease:

global class deleteOldMassLogs implements Database.Batchable<sObject> { // created to bulk delete records - use with care!

global final String QueryChild;
global final String QueryParent;

global deleteOldMassLogs() {
    QueryChild = 'select id from dca_mass_action__Mass_Action_Log__c where createddate < Date.Today().addDays(-7) and dca_mass_action__Parent_Log__c <> null';
//        QueryParent = 'select id from dca_mass_action__Mass_Action_Log__c where createddate < Date.Today().addDays(-7)';
}

global Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator(QueryChild);
}

global void execute
    ( Database.BatchableContext bc 
    , List<dca_mass_action__Mass_Action_Log__c> scope
    ) {
    delete scope;
}

global void finish(Database.BatchableContext bc) {}
}

Once all the child records are deleted, how can I delete the parent as well? in the same batch?

1 Answer 1

1

You can use the same batch, just remember that you should check if there are any remaining children left. Something like this should work:

Set<Id> parentIds = new Set<Id>();
for(dca_mass_action__Mass_Action_Log__c record: scope) {
  parentIds.add(record.dca_mass_action__Parent_Log__c);
}
delete scope;
delete [SELECT Id 
  FROM dca_mass_action__Parent_Log__c 
  WHERE Id IN :parentIds AND 
   Id NOT IN (
     SELECT dca_mass_action__Parent_Log__c FROM dca_mass_action__Mass_Action_Log__c
   )
];

I guessed the parent object name, so you may need to make appropriate changes.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .