Replies: 1 comment
-
Figured this out using custom filters and having: @derive {
Flop.Schema,
filterable: [
:pet_count_eq
],
sortable: [...],
adapter_opts: [
custom_fields: [
pet_count_eq: [
filter: {CustomFilters, :count_filter, [source: :pets]},
ecto_type: :integer,
operators: [:==]
]
]
]
} schema "owners" do
field :pet_count, :integer, virtual: true
timestamps()
end query =
from(owner in Owner,
left_join: pets in assoc(owner, :pets),
as: :pets,
group_by: [pets.id, owner.id],
select_merge: %{
pet_count: count(pets.id)
}
)
Flop.validate_and_run(query, params, for: Owner) defmodule CustomFilters do
import Ecto.Query
def count_filter(query, %Flop.Filter{value: count, op: op}, opts) do
source = Keyword.fetch!(opts, :source)
position = named_binding_position(query, source)
case op do
:== -> having(query, [{t, position}], count(field(t, :id)) == ^count)
:<= -> having(query, [{t, position}], count(field(t, :id)) <= ^count)
:<= -> having(query, [{t, position}], count(field(t, :id)) >= ^count)
_ -> query
end
end
defp named_binding_position(query, binding) do
query.aliases
|> Map.get(binding)
end
end |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
So following https://hexdocs.pm/flop/Flop.Schema.html#module-filtering-by-calculated-values-with-subqueries I was almost able to get filtering working with calculated values.
The problem I'm running into now is that since I'm using a left lateral join (as opposed to an inner lateral join), I can't count nil as a 0, thus not allowing me to search for counts of "0".
Beta Was this translation helpful? Give feedback.
All reactions