How to put rows returned from ecto query to hierarchical structure?

I have a Folders model that has a hierarchy with a parent_id key. I have a parent_path (ltree) field in it which has all the parent ids in it. I am using ltree type/extension for this. Now when I query the data I get rows. How can I put these folders in hierarchy/json structure using their parent ids?

schema "folders" do
    field :name, :string
    field :parent_path, :string

    belongs_to :parent, DServer.Folder
    has_many :childs, DServer.Folder, foreign_key: :parent_id
end

I followed these guides guide1 and guide2

2 Likes