peck

peck

Ecto CTE Recursively preload children

Hi everyone. I’m trying to wrap my head around using the CTE functionality in Ecto and I haven’t quite been able to figure it out by looking at the documentation. I’m working on building a simple nested comment system to try it out.

defmodule Comment do
  schema "comments" do
    field :body, :string

    has_many :children, {"comments", __MODULE__}, foreign_key: :parent_id

    belongs_to :parent, __MODULE__

    timestamps()
  end

end

I’d like to be able to get all the childen comments for a given comment, and all their children, and so on.

Looking at the Ecto docs, https://hexdocs.pm/ecto/Ecto.Query.html#with_cte/3-recursive-ctes, I’ve come up with this:

comment_tree_initial_query = Comment |> where([c], is_nil(c.parent_id))

comment_tree_recursion_query = Comment |> join(:inner, [c], ct in "comment_tree", on: c.parent_id == ct.id)

comment_tree_query = comment_tree_initial_query |> union_all(^comment_tree_recursion_query)

Comment |> recursive_ctes(true) |> with_cte("comment_tree", as: ^comment_tree_query)

Which seems to be in the right direction, but this just gives me back all comments in a flat list, vs them being loaded into children fields. I must be missing something simple, but I cannot quite figure out what.

Most Liked

seanwash

seanwash

Perhaps https://github.com/coryodaniel/arbor could be of some use?

dhony

dhony

I didn’t test yet, but maybe this is what you are looking for:

Self-reference many-to-many

yuchunc

yuchunc

CTE is part of the Postgres’ feature, and is intended to return a flat list.

As for nesting, I think the first step here is to think about how deep you want the query to go, having infinite depth could cause unexpected problem down the road.

That being said, we can use preload to get what we need. I did this for my company’s use case:

def tree_traversal(query, :nested} do
    preload =
      Enum.reduce(1..@default_traverse_layer, :descendants, fn _, acc ->
        [descendants: acc]
      end)

    preload(query, ^preload)
end

Record
|> tree_traversal(params.include_descendants) # we allow for :flat or :nested
peck

peck

:slight_smile:

I guess this functionality is a little less used than I thought. I’ll find some more time to dig in and see if I can get a solution to post here for others to reference later.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

We're in Beta

About us Mission Statement