Put conditional clause dynamically in where query

I got a list of maps like this:

 [%{"id" => 1}, %{"name" => "John"}]

I want to insert them in where query. These maps can be of any size.
The end query should be like this:

 From q in table,
 where: q.id == ^1 or q.name == "John"

I cannot hard code the above query due to the dynamic size of the list.

The end goal is to add each map with or inside where. I cannot use or_where due to requirements constraint.

Dynamics don’t solve this for me.

Is there any solution or workaround.

Any help or suggestion will be much appreciated.

Why though? This is exactly what the dynamic macro is for.


Yeah this seems precisely the use case of a dynamic:

where = Enum.reduce(conditionals, false, fn {key, value}, acc ->
  dynamic([q], acc or field(q, ^key) == ^value))

from q in table,
where: ^where

Thanks I will take a look into dynamics again.

1 Like