Cascade delete

default discord avatar
wojciechkrol
last year
1 3

Is it possible to delete a record with all his relations (cascade delete) without using hooks to delete each related record?

  • discord user avatar
    jmikrut
    Payload Team
    last year

    Hey @wojciechkrol — yes, this is possible! You'll need to write some hooks to do it. You could write a hook that can be used to traverse your collection schema and find any relationship fields, and for each one, you'd read the value of the relationship field and then delete all related documents using Payload's local API.

    Know what I mean?

    1 reply
  • discord user avatar
    jmikrut
    Payload Team
    last year

    Sorry, I didn't see that you specified without hooks. Honestly though I think that's probably the best way to do this. It could even be wrapped up as a neat little plugin.

    We don't have any use for this at the moment, but if one of our own projects needs it, we'll certainly build it into a plugin and make it public. If you do so, please share it! It shouldn't be too hard to build.

  • default discord avatar
    wojciechkrol
    last year

    Hej @jmikrut,

    Thank you for your answer. I will try to make a universal hook for this and let you know if I was successful :)

  • default discord avatar
    bencun
    10 months ago

    This would be extremely helpful to have as an option to enable on a per-collection basis where a collection would then be able check for any relationship type fields referencing itself when deleting an item.
    While I do understand a hook could resolve this having a built-in solution should, in my opinion, be of a very high priority since it would prevent end-users from breaking stuff (e.g. broken media, broken links etc).

    1 reply
    discord user avatar
    DanRibbens
    Payload Team
    10 months ago

    I started working on this then I got covid and my wife had a baby.

    #1209

    If somebody wants to fork off my PR, this is up for grabs. Otherwise I'll finish it after finishing the admin UI translations.

Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.