[SalesForce] Deleting all related list when a record is deleted in lookup

Good day everyone I have a problem in regards with deletion. This is my scenario. I have a custom object let say as AccountParent__c. I also created a lookup field in my Account object which is related to my AccountParent__c object. One AccountParent__c record has many Accounts.And what I want is that when I delete a AccountParent__c record, all account related to it will also be deleted.What is the best thing I have to do ? At the moment I've created a batch process for deleting the account and when there is a deletion for AccountParent__c record, a trigger will call the batch process for account deletion. But it seems it is not working. I guess the reason is that the AccountParent__c is already deleted but the batch process is still running.(I use batch because in my case there are possibilities that my related records are more than 10000)Do you have any idea how to solve my problem ? Below is a sample code for my trigger.

trigger deletionAcc on AccountParent__c (before delete) {
  for (AccountParent__c theold : Trigger.old) {

      // below is the batch use to delete all related list 
      delBatch b = new delBatch(String.valueOf(theold.Id)); 
      database.executebatch(b);
 }
}

please help.Thank you…

Best Answer

I am not writing complete code for you suppose you have

List<Account> accList ;// list of child record which we need to do delete 
if(accList.size() < 10000)
    delete accList;
else {
    while(accList.size() > 0) {
     integer count = 1;
     List<account> tempList = new Account();
     for(integer counter = 0 ; counter < accList.size()) {
         tempList.add(accList[counter]);
         accList.remove(remove);
         count++;
         if(count == 10000)
         break;
        }
       if(tempList.size() > 0)
          delete tempList;
    }
}

As it is not optimize code because it has DML inside for loop but it will work for you. If you have more then millions record then you will hit the limit.