awright415

awright415

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

krasenyp
You probably already know that <span>{nil}</span> in a HEEX template produces <span> </span> when rendered. I fin...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
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
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews