凤凰城同一张桌子上的多对多

Mar*_*van 2 many-to-many elixir ecto phoenix-framework absinthe

使用 Ecto v2.2.6、Phoenix 1.3

我有一张人表(碰巧彼此有关系),还有一张人的关系表。关系表在一列中列出父项的 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
Run Code Online (Sandbox Code Playgroud)

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

  schema "relationships" do
    field :parent_id, :id
    field :child_id, :id
    timestamps()
  end
Run Code Online (Sandbox Code Playgroud)

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

  schema "relationships" do
    belongs_to :person UserRelations.Accounts.Person 
    belongs_to :person UserRelations.Accounts.Person 
    timestamps()
  end
Run Code Online (Sandbox Code Playgroud)

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

编辑

根据建议,我已经像这样设置了架构:

  schema "relationships" do
    belongs_to :parent UserRelations.Accounts.Person 
    belongs_to :child UserRelations.Accounts.Person 
    timestamps()
  end
Run Code Online (Sandbox Code Playgroud)

我也尝试对 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
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试访问这些关系时(我通过 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
Run Code Online (Sandbox Code Playgroud)

Dog*_*ert 5

  1. 两个belongs_to 关系的名称需要不同。例如:

    belongs_to :child, UserRelations.Accounts.Person 
    belongs_to :parent, UserRelations.Accounts.Person 
    
    Run Code Online (Sandbox Code Playgroud)

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

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

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

    , join_keys: [parent_id: :id, child_id: :id]
    
    Run Code Online (Sandbox Code Playgroud)

    对于第二个:

    , join_keys: [child_id: :id, parent_id: :id]
    
    Run Code Online (Sandbox Code Playgroud)