【问题标题】:Many-to-many on the same table in Phoenix凤凰城同一张桌子上的多对多
【发布时间】: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


【解决方案1】:
  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]
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2012-05-23
    • 2017-07-21
    • 2017-03-07
    相关资源
    最近更新 更多