Search code examples
elixirecto

Cascade delete with many-to-many in Elixir


I have a (PostgreSQL) database with tables fd_feed, fd_tag and the joining table fd_feed_tags.

I have followed these Elixir guides to set up my database: https://hexdocs.pm/ecto/constraints-and-upserts.html and https://hexdocs.pm/ecto/Ecto.Schema.html#many_to_many/3-join-schema-example . Here is a snap of my database schema: https://slack-files.com/T03EPRA2X-F012Y9W1VNF-286b7fddcd

How do I configure elixir migrations or schemas so that when I delete the last parent (fd_feed) of an fd_tag, the tag is deleted from the database?


Solution

  • You set on_delete: :delete_all on the foreign key:

    add(:fd_feed_id, references(:fd_feed, on_delete: :delete_all))
    

    https://hexdocs.pm/ecto_sql/Ecto.Migration.html#references/2