If I have a form with filters filtering entities by some field and I want to add a group of or_where closes to the query dynamically.
And the query could already have some where closes which I want my group of or_where to be separated from by AND operator in db query.
So, I’d like to build the function like:
def add_composite_where_to_query(query, field_name, values) do
# here is something I can't figure out..
end
This function should add where closes to query like:
SELECT * from entities e where (e.field1=‘value1’ OR e.field1=‘value2’) AND (e.field2=‘value3’ OR e.field2=‘value4’ OR …)
I’ve already tried many ways, but no luck.
As examples of what didn’t work:
def add_composite_where_to_query(query, field_name, values) do
Enum.reduce(values, query, fn(value, acc) ->
or_where(acc, [q], field(q, ^field_name) == ^value)
end)
end
def add_composite_where_to_query(query, field_name, values) do
dynamic = Enum.reduce(values, query, fn(value, dynamic) ->
or_where(dynamic, association, ^field_name == ^value)
end)
where(query, ^dynamic)
end
def add_composite_where_to_query(query, field_name, values) do
dynamics = Enum.reduce(values, [], fn(value, dynamics) ->
dynamic([q], field(q, ^field_name) == ^value)
end)
where(query, ^dynamics)
end