I have an entity Node
that references itself in order to create a tree-like structure.
Here is the migration:
create table(:nodes) do
add :name, :string, null: false, size: 64
add :parent_id, references(:nodes, on_delete: :nothing)
end
And here the schema definition:
schema "nodes" do
field :name, :string
belongs_to :parent, Node
has_many :children, Node, foreign_key: :parent_id
end
I am trying to load the entire tree using this approach:
root_nodes = Repo.all(
from n in Node,
where: is_nil(n.parent_id) # Root nodes don't have a parent
)
nodes = Enum.map(root_nodes, fn(n) ->
Ecto.build_assoc(n, :children, load_children(n.id))
end)
Where:
defp load_children(parent_id) do
nodes = Repo.all(
from n in Node,
where: n.parent_id == ^parent_id
)
if nodes != [] do
# If children aren't empty, apply recursively
nodes = Enum.map(nodes, fn(n) ->
Ecto.build_assoc(n, :children, load_children(n.id))
end)
end
nodes
end
but I get:
** (FunctionClauseError) no function clause matching in Ecto.drop_meta/1
Generally, I think I struggle with understanding of how Ecto ORM should be used. Most of the tutorials show only examples of how to fetch isolated rows, or with one level of preloading. How should I load a tree-like structure? Thank you for any help.