[SalesForce] Cascade delete records

I have one object, for example Area. It has two lookup relationships to itself, Parent__c, Child__c. In result I can create record with Parent and Child parameters. I am trying build hierarchy.

And when I delete a record, I want delete all of its children, and children of its children, ad infinitum. Long story short, imitation of Master Detail relationship. Why don't I use Master Detail? Because a Master Detail relationship cannot refer an object to itself.

How can I resolve?

Best Answer

I've only done this for immediate children (admittedly for separate parent/child SObjects - see Dmitriy's comment), but assume this trigger approach will work:

trigger AreaTrigger on Area__c (before delete) {
    Set<Id> ids = Trigger.oldMap.keySet();
    delete [
            select Id from Area__c
            where Parent__c in :ids
            or Parent__r.Parent__c in :ids
            or Parent__r.Parent__r.Parent__c in :ids
            or Parent__r.Parent__r.Parent__r.Parent__c in :ids
            or Parent__r.Parent__r.Parent__r.Parent__r.Parent__c in :ids
            ]);
}

Only up to 5 levels of parent relationship can be traversed in the above manner, so if you need to support arbitrary depth, a looped solution where multiple queries are done will be needed.

See e.g. A Deeper look at SOQL and Relationship Queries on Force.com for more explanation about relationships (__r values).