Many to Many joins with Ecto and Elixir

Ecto is an DSL for writing queries and interacting with databases in Elixir.  It has a style similar to ActiveRecord, but since there aren’t objects, you can’t really call it an ORM.

Like ActiveRecord, it has has_many and belongs_to, but it doesn’t have has_many :through yet. Here is how I implemented a DAG using a many-to-many join in Ecto anyways

The basic idea is I have a Nodes table.  And each Node can have multiple parents and multiple children.  The most straightforward implementation of this is to have a many-to-many join table and then use that with INNER JOIN to query for parents or children.

First, I needed to create the tables using Ecto’s migration feature.

Then I define the models using the Ecto model DSL.

This wasn’t quite enough though. I ran into trouble getting Node to preload its children and parents via NodeToNode. I ended up adding help functions to the Node module.

This now lets me write an association.

This works as far as I can tell with my unittests. I’m not completely comfortable with Ecto’s association proxy, so there might be a better way to do this that is more idiomatic. I hope that has_many :through support is added soon so I can concentrate on my business logic instead of mundane joins. I think more documentation of reading and writing associations is necessary.

If you know a better way to express this, please let me know.

3 thoughts on “Many to Many joins with Ecto and Elixir

  1. Thanks for the link to the many_to_many docs. What’s still not clear to me is how to actually use many_to_many associations for CRUD operations. Are there any full examples that anyone could point to? Is there a developers Guide page on this somewhere?

Leave a Reply