Count unique ids inside aggregation

Sup

I have a Property module with the relationship:

relationships do
 #...

  has_many :offers, Offer

 #...
end

I would like to do something like:

  aggregates do
    count :total_unique_offers, :offers do
     # filter distinct(:offeror_id) ????
    end
  end

I have this calculation, which already works, but it doesn’t seem super optimized.

Is there a way to perform this calculation via aggregate?

defmodule TotalUniqueOffers do
  @moduledoc false

  use Ash.Calculation

  @impl true
  def load(_query, _opts, _context), do: [:offers]

  @impl true
  def calculate(properties, _, _) do
    Enum.map(properties, fn %{offers: offers} ->
      offers
      |> Enum.uniq_by(& &1.offeror_id)
      |> Enum.count()
    end)
  end
end
count :total_unique_offers, :offers do
  field :offerer_id
  uniq? true
end
1 Like

Fits like a glove :bowing_man:.

Thank you so much!!!

1 Like