凤凰中的级联删除

Cascade delete in phoenix

我有 3 个模型:

schema "m1s" do
  (...)
  has_many :m2s, MyApp.M2, on_delete: :delete_all
end

schema "m2s" do
  (...)
  belongs_to :m1s, MyApp.M1
  many_to_many :m3s, MyApp.M3, join_through: MyApp.M3sM2, on_delete: :delete_all
end

schema "m3s" do
  (...)
  many_to_many :m2s, MyApp.M2, join_through: MyApp.M2sM3
end

schema "m2s_m3s" do
  (...)
  belongs_to :m2, MyApp.M2
  belongs_to :m3, MyApp.M3
end

从 M1 删除会触发从 M2 删除。

从 M2 删除会触发从 M2sM3 删除。

所以我假设从 M1 中删除会触发从 M2sM3 中删除。

但是当我尝试删除 M1 时,如果 m2s_m3 table 中有元素,我会得到这个错误:

** (Postgrex.Error) ERROR 23503 (foreign_key_violation): update or delete on table "m2s" violates foreign key constraint "m2s_m3s_m2_id_fkey" on table "m2s_m3s"

table: m2s_m3s
constraint: m2s_m3s_m2_id_fkey

我错过了什么?有没有办法在 Phoenix 中进行级联删除?谢谢!

您正在寻找的 属性 通常称为传递性(M1 x M2 和 M2 x M3,因此 M1 x M3)。如果您有可能更改数据库架构(例如,使用您的迁移文件),那么您应该考虑让数据库来处理。在您有 references(:m1s) 的迁移中,您可以添加 on_delete: :delete_all 导致 references(:m1s, on_delete: :delete_all)。其他表也是如此。

另见 https://hexdocs.pm/ecto/Ecto.Schema.html :nilify_all 和 :delete_all 不会级联到子记录,除非通过数据库迁移设置。