awright415

awright415 OP

I needed to figure out a way to recursively preload child records from a many_to_many relationship with Ecto, but all the discussions I saw were limited to hierarchical, self-join scenarios. This seemed very doable with a recursive CTE, though, so I got to work.

I’m new to Elixir, so I might’ve missed a better solution. But I went with passing a preloading function to Ecto.Query.preload/3.

The recursive CTE turns the simple many-to-many join table into a (partial) closure table. Then, within the preload function, I’m querying the CTE for all the child records and building out the fully nested Ecto structs.

That’s the version of the solution that I put into a gist to share here. But, for my actual use case, I took the extra step of creating a recursive view for the full closure table. Then I made a separate Ecto schema that models the rows of the closure table as Edges in the graph. This leaves the option of later making a materialized view of the closure table if performance requires it.

At some point, I hope to do a proper blog post about this. But in the meantime, I wanted to get a solution out there, in case someone else has a similar use case.

Where Next? Top

Trending in Guides/Tuts Top

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement