0

Simple Scenario..
Object B has a LookUp relation to Object A. On deletion of object A, delete all records of object B.

trigger deleteObjectBrecords on ObjectA (after delete){
      List<objectB__c> recordsTodelet = new list<objectB> ();

      for(ObjectA a : [select Id,(select Id from objectbs___r) from objectA__c    where Id IN:Trigger.OldList ALL ROWS]){
      recordsTodelete.add(a.objectbs___r)
   }
   delete recordsTodelete;
}

a.objectbs___r is coming blank because on deletion of object A all the relationship links with the object B are gone.

the issue is inner query is not returning the records. It's working fine in the Query editor console but not in the trigger. Is there some kind of limitation on inner query for deleted records. I believe, inner query not working because once deleted all the links are gone.If thats the case,should we write an trigger on before delete ? will that be a best Pratice ?

  • Just a thought. You can get Cascade delete enabled for lookup relationships which will automatically delete child records for lookups without need of any code/testclass/deployment. Link – manjit5190 Feb 14 '17 at 8:10
  • Yeah. I have to raised a request to Sales force to enable that but didn't want to because of security reason. – Ankit Khandelwal Feb 14 '17 at 8:12
  • Then you might want to move your delete code inside a with sharing class because triggers will run in system context and it will also bypass sharing settings – manjit5190 Feb 14 '17 at 8:14
1

You need to run this query on Before delete not after delete.

trigger deleteObjectBrecords on ObjectA (before delete){
      List<objectB__c> recordsTodelet = new list<objectB> ();

      for(ObjectA a : [select Id,(select Id from objectbs___r) from objectA__c    where Id IN:Trigger.OldList ALL ROWS]){
      recordsTodelete.addAll(a.objectbs___r)
   }
   delete recordsTodelete;
}

then you will find the child records and can delete them.

  • 1
    small correction here recordsTodelete.add(a.objectbs___r) will be addAll(). recordsTodelete.addAll(a.objectbs___r) – Ratan Paul Feb 14 '17 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.