【发布时间】:2018-03-19 12:42:58
【问题描述】:
使用 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
现在,我要在关系模式中添加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
但是,当我尝试访问这些关系时(我正在通过苦艾酒/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
【问题讨论】:
-
只需将第二个重命名为
belongs_to :child? -
@Dogbert 试图实现它。请参阅上面的编辑。
-
我认为您需要将
join_keys: [parent_id: :id, child_id: id]添加到第一个many_to_many并反向添加([child_id: :id, parent_id: :id])到第二个。 -
@Dogbert Perfect,它完全按照说明工作。如果您将这两个 cmets 转换为答案,我将标记为正确。
标签: many-to-many elixir phoenix-framework ecto absinthe