elixir - 如何使用 Ecto 对模型删除设置 foreign_key_constraint?

标签 elixir ecto

我有 2 个模型,UserRole用户 has_many 角色。我还设置了外键约束(如果有任何用户拥有该角色,则不能删除角色)。

我在尝试实现时遇到错误

Role
|> Repo.get(id)
|> Repo.delete

错误是:

 ** (Ecto.ConstraintError) constraint error when attempting to delete struct:

     * foreign_key: users_role_id_fkey

 If you would like to convert this constraint into an error, please
 call foreign_key_constraint/3 in your changeset and define the proper
 constraint name. The changeset defined the following constraints:

     * foreign_key: roles_users_fkey

我不知道如何在删除时添加此 foreign_key_constraint。我试着自己写,比如:

def delete_changeset(struct) do
  struct
  |> cast(%{}, [])
  |> foreign_key_constraint(:users)
end

并将其插入到 |> Repo.delete 之前。但它不起作用。如何在此处添加 foreign_key_constraint

更新

迁移文件:

defmodule MyApp.Repo.Migrations.CreateRole do
  use Ecto.Migration

  def change do
    create table(:roles) do
      add :name, :string, null: false

      timestamps()
    end

    create unique_index(:roles, [:name])
  end
end

为用户添加role_id:

defmodule MyApp.Repo.Migrations.AddRoleIdToUsers do
  use Ecto.Migration

  def up do
    alter table(:users) do
      add :role_id, references(:roles, on_delete: :nothing)
      remove :role
    end
  end
end

最佳答案

我解决了

|> foreign_key_constraint(:users, name: :users_role_id_fkey)

删除变更集。但它返回可怕的错误

%{ "users" => ["doesn't exist"] }

在变更集中。我勒个去?我想在变更集中纠正错误

关于elixir - 如何使用 Ecto 对模型删除设置 foreign_key_constraint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39217867/

相关文章:

metaprogramming - 将 AST 插入到 quote do end block 中而不取消引用它

elixir - `virtual: true` 对嵌入式架构有影响吗?

elixir - 在Ecto中按DateTime查询

phoenix-framework - Phoenix/Ecto - 未检索 Postgres 数组列中的整数值

mysql - 映射到MySql BIGINT的Ecto或Elixir数据类型

elixir - 在 Phoenix 项目中将辅助功能放在哪里?

elixir - 有没有办法在 Phoenix 启动服务器时自动启动浏览器?

Elixir/Phoenix 扫描目录以查找目录

json - Elixir 将 JSON 列表解码为结构

postgresql - 无法混合 ecto.create,角色 'postgres' 不存在