Elixir Ecto:如何创建一个自引用外键



在Ecto迁移中,实现引用自己表的外键的正确方法是什么?

例如,我想创建一个表,其中任何一行都可以引用同一表中的"父"行。(分层数据的一种方法;还有许多其他方法。)

但是当我的变更集中有这个时,我在运行mix ecto.migrate:时会遇到很多错误

create_if_not_exists table(:perms, prefix: :accts) do
  add :title, :string, size: 64, null: false
  add :description, :text
  add :parent_id, :integer, references(:perms)
end

在GenServer终止之前,错误消息以(UndefinedFunctionError) undefined function Ecto.Migration.Reference.fetch/2 (Ecto.Migration.Reference does not implement the Access behaviour)开头。(这发生在ecto 1.1.5和2.0.0-beta2下。)

答案是一个简单的错误:试图为外键列指定列类型会导致错误。正确的语法是(注意缺少:integer原子):

create_if_not_exists table(:perms, prefix: :accts) do
  add :title, :string, size: 64, null: false
  add :description, :text
  add :parent_id, references(:perms)
end

最新更新