Ecto Composable Queries

For a while, I wondered how it was possible to prepare a query in Ecto that involves a join, then pass that query on and add a condition based on that join.

q = (from r in Rule, join: e in Event, on: e.rule_id ==
(from e in q, where: == ^"Hello")

The above example will look for the name “Hello” on the Rule table, not the Event table. The answer is to use the where function, which accepts a list of bindings as the second argument.

where(q, [_, e], == ^"Hello")

Any bindings that you’ve prepared in the previous query will be passed in the order that they were joined.

Posted in Ecto, Elixir

Leave a Reply

Your email address will not be published. Required fields are marked *