【问题标题】:Elixir Ecto: How do I create a self-referential foreign key?Elixir Ecto:如何创建自引用外键?
【发布时间】:2016-04-11 04:29:38
【问题描述】:

在 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 下。)

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2016-10-26
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      相关资源
      最近更新 更多