Parent-child relationships on same schema

Using Ecto v2.2.6, Phoenix 1.3

I have a table of people (who happen to be related to each other), and another table of relations for those people. The relations table lists the id of the parent in one column, and the id of the child in another.

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

Now, I am about to add belongs_to relationships in the relationships schema (which currently looks like this)

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

I have set the schema up like this:

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

I have tried to do something similar with the Person schema as well:

  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

However, when I try to access these relationships (I am doing this through an absinthe/graphql schema), I see that it is looking for a user_id somewhere:

[error] Task #PID<0.400.0> started from #PID<0.395.0> terminating
** (Postgrex.Error) ERROR 42703 (undefined_column): column f2.user_id does not exist

Solved it. I put join_keys: in the many-to-many clauses in my users schema:

    many_to_many :parent_of, UserRelations.Accounts.Person, join_through: "relationships", join_keys: [parent_id: :id, child_id: :id]
    many_to_many :child_of, UserRelations.Accounts.Person, join_through: "relationships", join_keys: [child_id: :id, parent_id: :id]
2 Likes