Ecto.Query.or_where
You're seeing just the macro
or_where
, go back to Ecto.Query module for more information.
An OR where query expression.
Behaves exactly the same as where
except it combines with any previous
expression by using an OR
. All expressions have to evaluate to a boolean
value.
or_where
also accepts a keyword list where each key is a field to be
compared with the given value. Each key-value pair will be combined
using AND
, exactly as in where
.
Keywords example
from(c in City, where: [country: "Sweden"], or_where: [country: "Brazil"])
If interpolating keyword lists, the keyword list entries are combined using ANDs and joined to any existing expression with an OR:
filters = [country: "USA", name: "New York"]
from(c in City, where: [country: "Sweden"], or_where: ^filters)
is equivalent to:
from c in City, where: (c.country == "Sweden") or
(c.country == "USA" and c.name == "New York")
The behaviour above is by design to keep the changes between where
and or_where
minimal. Plus, if you have a keyword list and you
would like each pair to be combined using or
, it can be easily done
with Enum.reduce/3
:
filters = [country: "USA", is_tax_exempt: true]
Enum.reduce(filters, City, fn {key, value}, query ->
from q in query, or_where: field(q, ^key) == ^value
end)
which will be equivalent to:
from c in City, or_where: (c.country == "USA"), or_where: c.is_tax_exempt == true
Expressions example
City |> where([c], c.country == "Sweden") |> or_where([c], c.country == "Brazil")