Best way to sum in associations?

402 views
Skip to first unread message

Alex Jonsson

unread,
Jun 11, 2016, 11:45:12 AM6/11/16
to elixir-ecto
Hey! I've got two Ecto models like this:

defmodule Parent do
  schema
"parents" do
    field
:name, :string
    field
:is_test, :boolean

    has_many
:children, Child

    timestamps
 
end
end

defmodule Child do
  schema
"children" do
    field
:count, :float
    field
:value, :float

    belongs_to
:parent, Parent

    timestamps
 
end
end

When I list the Parents, I want to be able to show the total sum of the "value" properties if its' children. Which is the most efficient way to query this using Ecto?

Thanks!
Alex

José Valim

unread,
Jun 11, 2016, 12:33:23 PM6/11/16
to elixi...@googlegroups.com
If you are using Ecto 2.0-rc: parent |> assoc(:children) |> Repo.aggregate(:sum)
--
You received this message because you are subscribed to the Google Groups "elixir-ecto" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-ecto...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-ecto/e97dcc0c-956c-4f32-92fc-bc0e4bb6b5ec%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--


José Valim
Skype: jv.ptec
Founder and Director of R&D

Alex Jonsson

unread,
Jun 11, 2016, 5:17:17 PM6/11/16
to elixir-ecto, jose....@plataformatec.com.br
Thanks José! Actually I realised that Enum.sum worked just fine since I already populated the children. But the aggregate function was new to me and amazing for another use case :)

Great work,
Alex
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-ecto+unsubscribe@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages