Elixir 删除引用的数据库记录

Elixir 删除引用的数据库记录,elixir,ecto,Elixir,Ecto,我有两张桌子: 用户: id username password unique_index username (the schema has a has_many other) id user_id - references(:users) foo index user_id (the schema has a belongs_to user) 其他: id username password unique_index username (the schema has a has

我有两张桌子:

用户:

id
username
password

unique_index username

(the schema has a has_many other)
id
user_id - references(:users)
foo

index user_id

(the schema has a belongs_to user)
其他:

id
username
password

unique_index username

(the schema has a has_many other)
id
user_id - references(:users)
foo

index user_id

(the schema has a belongs_to user)
在“其他”的变更集中,我有这个

model
|> cast(params, @req, @opt)
|> foreign_key_constraint(:user_id)
我在这一点上的假设是“其他”的外部模型需要一个“用户”与之关联才能存在(这就是我想要的)

但我的第二个假设是,如果我删除“用户”记录,那么所有相关的“其他”记录都将被删除(通过级联删除)

实际发生的情况是,当试图删除“用户”记录时,我有一个EXTO.CONSTRAINT错误(我假设是因为有一个“其他”记录与该用户关联)

那么,我将如何让它以我想要的方式工作,即:

  • “用户”可以独立创建
  • 可以创建“其他”,但必须属于“用户”
  • 删除“其他”时,不会影响其他任何内容
  • 当“用户”被删除时,它也会删除所有相关的“其他”记录

本质上是对用户引用它的任何项目进行级联删除

我发现,在has many上,您可以传递on_Delete选项

所以有很多看起来像这样

has_many :other, Project.Other, on_delete: :delete_all
医生很有帮助:p


您可以使用在架构中指定的方式执行此操作:

has_many :other, Project.Other, on_delete: :delete_all
但是,在迁移过程中,使用以下方法可能会更好:

这将使用数据库外键约束,并在
的许多
文档中提到:

:on_delete-删除父模型时对关联采取的操作。可能是:nothing(默认),:nilify_all和:delete_all。注意:在创建引用时,也可以在迁移中设置on_delete。如果支持,则首选通过迁移依赖数据库

您可以使用以下命令更改现有索引:

drop_if_exists index(:others, [:user_id])
alter table(:others) do
  modify :user_id, references(:users, type: :uuid, on_delete: :delete_all)
end

现有指数的解决方案目前(2018年6月)似乎不起作用。此解决方案在这里起作用: