When querying via Ecto.Query.where/3
is it possible to query by something other than equality when using a keyword list? Like greater than or equal to?
When you say keyword list do you mean |> where(foo: 1)
? Sorta, but you need to do |> where([a], a.foo > 5)
.
3 Likes
Yes, something like where(queryable, foo: 1)
. There’s no way to do something like where(queryable, foo: {:>=, 1})
? It has to be through the bindings?
1 Like
Here’s what I’ve come up with so far.
defmodule Helpers.Query do
require Ecto.Query
def compare({ field, { :!= , value } }) do
Ecto.Query.dynamic([q], field(q, ^field) != ^value)
end
def compare({ field, { :<, value } }) do
Ecto.Query.dynamic([q], field(q, ^field) < ^value)
end
def compare(expression) do
[expression]
end
end
Would allow something like.
expression = Helpers.Query.compare({ :field_1, { :!=, "some value" } })
Ecto.Query.where(MySchema, ^expression)
Curious if someone has an idea on making this simpler or cleaning this up.
Check out ecto_filter library, it may be helpful for your use case.
1 Like