valyukov

valyukov

Dynamic fields in Ecto queries

Hi there,

How I can build queries with dynamic fields assignment in Ecto?
I try to do next thing:

import Ecto.Query
field = :id
value = 1

from(o in Order, where: o[field] != ^value)

** (Ecto.Query.CompileError) `o[field]` is not a valid query expression
    (ecto) expanding macro: Ecto.Query.where/3
           iex:6: (file)
    (ecto) expanding macro: Ecto.Query.from/2
           iex:6: (file)

how you can see it doesn’t work, but who cares? keyword syntax allow to do next things:

from(o in Order, where: ^[{field, value}])

and this works fine, but only for simple cases, it doesn’t allow neglect syntax (!=), like, is not, etc.

I don’t give up, and try to apply some metaprogramming magic:

(quote do: unquote(Order) |> where([q], q.unquote(field) == ^unquote(var!(value)))) |> Code.eval_quoted |> elem(0)

And it works perfect, however I need to make join with dynamic association, the next example throw exception and I have no idea how to solve it:

assoc = :transaction

(quote do: unquote(Order |> Ecto.Queryable.to_query) |> join(:inner, [r], l in assoc(r, unquote(var!(assoc)))) |> where([r, l], l.unquote(field) == ^unquote(var!(value)))) 
|> Code.eval_quoted 
|> elem(0)
** (CompileError) nofile: invalid quoted expression: #Ecto.Query<from o in Store.Order>
      (ecto) expanding macro: Ecto.Query.where/3
             nofile:1: (file)
    (elixir) expanding macro: Kernel.|>/2
             nofile:1: (file)

but if I quote module all works fine

how we see there is only one problem that join macros throw error when I try to pass Ecto.Query struct to it. Next snippet works well, but in my app I would like to pass exactly Ecto.Query to join.

assoc = :transaction

(quote do: unquote(Order) |> join(:inner, [r], l in assoc(r, unquote(var!(assoc)))) |> where([r, l], l.unquote(field) == ^unquote(var!(value)))) 
|> Code.eval_quoted 
|> elem(0)

Schemes:

defmodule Order do
  use Ecto.Schema
  schema "orders" do
    has_one :transaction, Transaction
  end
end

defmodule Transaction do
  use Ecto.Schema

  schema "transactions" do
    belongs_to :order, Order
  end
end

Data:
orders: [{id: 1}, {id: 2}]
transactions: [{id: 1, order_id: 1}, {id: 2, order_id: 2}]

Marked As Solved

Linuus

Linuus

To use dynamic fields you can use the field macro.

thing = :points
from a in Foo, where: field(a, ^thing) > 8
19
Post #2

Also Liked

valyukov

valyukov

It works perfect! Thank you!

mosiac05

mosiac05

Thanks, works fine.

Where Next?

Popular in Questions Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
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
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement