Phoenix 中同一 table 上的多对多

Many-to-many on the same table in Phoenix

使用 Ecto v2.2.6,Phoenix 1.3

我有一个 table 人(他们碰巧彼此有关系),还有另一个 table 这些人的关系。关系 table 在一列中列出了父项的 ID,在另一列中列出了子项的 ID。

mix phx.gen.json Accounts Person persons name:string age:integer
mix phx.gen.json Accounts Relationship relationships parent_id:references:persons child_id:references:persons

现在,我要在关系模式中添加 belongs_to 关系(目前看起来像这样)

  schema "relationships" do
    field :parent_id, :id
    field :child_id, :id
    timestamps()
  end

但是如果不能显式设置 id,它看起来像这样(这似乎不起作用)

  schema "relationships" do
    belongs_to :person UserRelations.Accounts.Person 
    belongs_to :person UserRelations.Accounts.Person 
    timestamps()
  end

如何编写关系模式以便捕获这些 belongs_to 关系?

编辑

我按照建议设置了这样的模式:

  schema "relationships" do
    belongs_to :parent UserRelations.Accounts.Person 
    belongs_to :child UserRelations.Accounts.Person 
    timestamps()
  end

我也尝试过对 Person 模式做类似的事情:

  schema "persons" do
    field :age, :integer
    field :name, :string
    many_to_many :parent_of, UserRelations.Accounts.Person, join_through: "relationships"
    many_to_many :child_of, UserRelations.Accounts.Person, join_through: "relationships"
    timestamps()
  end

但是,当我尝试访问这些关系时(我是通过 absinthe/graphql 模式执行此操作),我发现它正在某处寻找 person_id:

[error] Task #PID<0.400.0> started from #PID<0.395.0> terminating
** (Postgrex.Error) ERROR 42703 (undefined_column): column f2.person_id does not exist
  1. 两个belongs_to关系的名称需要不同。例如:

    belongs_to :child, UserRelations.Accounts.Person 
    belongs_to :parent, UserRelations.Accounts.Person 
    

    使用这些名称,Ecto 将正确推断出外键:child_idparent_id

  2. 对于 many_to_many,您需要向两者提供 join_keys,因为 Ecto 无法从关系名称和模式模块中推断出它。

    对于第一个,您需要添加:

    , join_keys: [parent_id: :id, child_id: :id]
    

    第二个:

    , join_keys: [child_id: :id, parent_id: :id]