[SalesForce] How to simulate cascade delete in trigger

I have two objects linked by a lookup. The objects are one-to-one and neither should exist without its counterpart. When one is deleted, I need the other to be deleted as well.

My plan was to put some logic in each objects' trigger. Here's what Obj 1's trigger looks like:

if (Trigger.isAfter && Trigger.isDelete) {
    for (Obj_1__c obj: Trigger.Old) {
        delete [select id from Obj_2__c where Obj_1__c = : obj.Id];
    }
}

The problem with this is that the lookup is cleared out before the After Delete trigger, since the deletion of Obj 1 has already taken place. And I'm afraid using a Before Delete trigger will cause similar logic in Obj 2's trigger to create a loop, attempting to delete its Obj 1 lookup.

Is there a better way to delete records that are paired by a lookup? I know there's a built-in cascade delete, but you have to submit a ticket to SF to enable that functionality.

Best Answer

The trick is to store the values beforehand. Simply set up a static variable to hold the old values before deletion, then delete them after deleting:

public class Stash {  // Don't use statics in triggers. They behave oddly.
    public static SObject[] pendDeletes;
}

// Trigger
trigger ... on ... (before delete, after delete) {
    if(Trigger.isBefore) {
        Stash.pendDeletes = [SELECT Id FROM Obj_2__c WHERE Obj_1__c IN :Trigger.old];
    } else {
        if(Stash.pendDeletes != null) {
            SObject[] temp = Stash.pendDeletes;
            Stash.pendDeletes = null;  // Avoid recursion
            delete temp;
        }
    }
}