Ecto 删除引用的数据库记录

Ecto delete referenced database record

我有 2 个表:

用户:

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)

在 "Other" 的变更集中我有这个

model
|> cast(params, @req, @opt)
|> foreign_key_constraint(:user_id)

此时我的假设是 "Other" ecto 模型需要一个 "User" 与之关联才能存在(这正是我想要的)

但我的第二个假设是,如果我删除 "User" 记录,那么所有关联的 "Other" 记录都将被删除(通过级联删除)

实际发生的是我在尝试删除 "User" 记录时有一个 Ecto.ConstraintError(我假设是因为有一个 "Other" 记录与该用户关联)

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

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

我想通了,有很多你可以传递一个 on_delete 选项

所以 has_many 看起来像这样

has_many :other, Project.Other, on_delete: :delete_all

文档很有帮助 :p

https://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3

您可以按照您在模式中指定的方式使用:

has_many :other, Project.Other, on_delete: :delete_all

但是,您最好在迁移时使用 references/2:

create table(:others) do
  add :user_id, references(:users, on_delete: :delete_all)
end

这将使用数据库外键约束并在 has_many 文档中提到:

:on_delete - The action taken on associations when parent model is deleted. May be :nothing (default), :nilify_all and :delete_all. Notice :on_delete may also be set in migrations when creating a reference. If supported, relying on the database via migrations is prefered

您可以更改现有索引:

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