script

script

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.
Thanks

Marked As Solved

OvermindDL1

OvermindDL1

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))
end)

from q in table,
where: ^where

Also Liked

LostKobrakai

LostKobrakai

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

script

script

Thanks I will take a look into dynamics again.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement