2

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?

1 Answer 1

4

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).

6
  • 1
    You could also create an Ultimate Parent formula.
    – Adrian Larson
    Jul 9, 2016 at 22:28
  • Its bad solution because, triggerrs not allow recursively delete itself records.
    – Leroy
    Jul 10, 2016 at 9:24
  • @Dmitriy OK. If you have a solution yourself now add it - you can accept your own answer - or if not someone else will hopefully answer.
    – Keith C
    Jul 10, 2016 at 9:27
  • Wow that's rude...and doesn't even seem like a valid objection.
    – Adrian Larson
    Jul 10, 2016 at 14:01
  • @Dmitriy You can write the delete code in a separate class which will be called multiple times as the trigger delete each child records Jul 10, 2016 at 18:35

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.