function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Harshavardhan Reddy 29Harshavardhan Reddy 29 

Apex Triggers to delete lookup relation child records

Hi I want to delete custom object records and also case records when account is deleted using trigger. Undelete the child records if account is undeleted the trigger works only for custome objects but case records are not deleted and undelted .Below is the trigger code.

trigger OrderDeletion on Account (before delete,after undelete) {
    
    List<Id> AccIds= new List<Id>();
   
    if(trigger.isbefore && trigger.isdelete){  
        for(Account acc: trigger.old){
            AccIds.add(acc.id);
        }
        List<AccountOrder__c> ordlist=[select id,name,AccountOrder__c from AccountOrder__c WHERE AccountOrder__c in:AccIds];
        if(ordlist.size()>0){
            delete ordlist;
        }
        
        List<Case> caselist = [select id from Case where Account.Id in:AccIds];
        if(caselist.size()>0){
            delete caselist;
        }
    }
    
    if(trigger.isAfter && trigger.isUndelete){
        for(Account acc: trigger.new){
            AccIds.add(acc.id);
        }
        
        List<AccountOrder__c> ordlist2=[select id,name,AccountOrder__c from AccountOrder__c WHERE AccountOrder__c in:AccIds AND isDeleted = true ALL ROWS];
        if(ordlist2.size()>0){
            undelete ordlist2;
        }
        
         List<Case> caselist1 = [select id from Case where Account.Id in:AccIds AND isDeleted = true ALL ROWS];
        if(caselist1.size()>0){
            delete caselist1;
        }
    }
}
Nayana KNayana K
List<Case> caselist1 = [select id from Case where Account.Id in:AccIds AND isDeleted = true ALL ROWS];
        if(caselist1.size()>0){
            delete caselist1;
        }

you are trying to undelete cases but have written delete caselist1;
So change this to 
 
List<Case> caselist1 = [select id from Case where AccountId in:AccIds AND isDeleted = true ALL ROWS];
        if(caselist1.size()>0){
            undelete caselist1;
        }