Elixir Ecto: Multiple Connections and Reusable / Compound Queries

In Ecto, you can make multiple / compound queries, like so:

defmodule AModel #... def anonymous(q), do: q |> where([am], is_null(am.user_id)) end 

See more examples in this post .

However, I am facing the problem of using multiple connections.

Suppose we have a circuit that looks like this:

  • AModel owned by BModel
  • BModel belongs to CModel
  • CModel belongs to DModel

The solution proposed in this article does not actually work with deep joins:

 q = DModel |> join(:inner, [dm], cm in assoc(dm, :c_models)) |> join(:inner, [_, cm], bm in assoc(cm, :b_models)) |> join(:inner, [_, _, bm], am in assoc(bm, :a_models)) |> AModel.anonymous 

Query functions accept the binding table as the first (second to join) argument. It contains the previous associations and, unfortunately, is closely related to the order of accession.

In our case, the anonymous function is intended for the start table. However, in the sample request, AModel is the 4th binding ...

Any idea or technique to get rid of this order dependency?

EDIT:

I get a response from the author of the blog. He told me that there is no other way to handle the bindings except by the position in the table. He also gave this article covering this fact.

But for God's sake, if order matters, why can't I create a name mapping above it that associates a name with a binding index?

This is too much to ask: p?

+6
source share
2 answers

Use named bindings

Ecto 3.0 added named bindings for this use case.

0
source

Perhaps create multiple join tables ?


EDIT: I see that maybe I was too brief. I want to say that you can create connection tables on the backend and then query them. This way you don't have to worry about creating joins in your Ecto code. Hope my answer becomes clearer.

-1
source

Source: https://habr.com/ru/post/1233862/


All Articles