Self Referencing Association in Phoenix / Ecto

OK, after trying this out in my Phoenix app I have a couple of comments to add to the code. So that others can benefit from this as well:

I was working on a Phoenix app called Studentmanager, so the model was actually called: Studentmanager.User and that needs to be added in the association as well.

defmodule Studentmanager.User do
  schema "users" do
    field :name

  belongs_to :teacher, Studentmanager.User
  has_many :students, Studentmanager.User, foreign_key: :teacher_id
  end
end

And here there is a slight correction needed to get the names correctly, teacher.students will give a list that Enumerable can handle.

teacher = Repo.get(User, 1) |> Repo.preload(:students)
Enum.map(teacher.students, &(&1.name))
#> ["Student John", "Student Jane"]

thanks again!

6 Likes