I have a query in Ecto the includes the sum of a column containing integers. I'm using MySQL as the database.
e.g.
result = Repo.one(
from v in Vote,
where: [post_id: 1],
select: sum(v.direction)
)
IO.inspect(result)
# Yields: #Decimal<5>
The result is returned from Ecto as a #Decimal<x>. When I encode this to json it's cast to a string. Ideally I'd like it as an integer, especially as the result will always be an integer from the database.
What's the best way to cast this?
Here's my schema:
schema "votes" do
field :direction, :integer
belongs_to :user, Linklet.User
belongs_to :link, Linklet.Link
timestamps()
end
I have managed to achieve the intended result by using MySQL's CONVERT function within a fragment, but it doesn't seem like the most robust approach:
result = Repo.one(
from v in Vote,
where: [post_id: 1],
select: fragment("CONVERT(?, SIGNED)", sum(v.direction))
)
Is there a better way?
Vote. - Aleksei MatiushkinDecimal.to_integer(result)? - Dogbertdirectioncolumn is an integer. I'm not sure why the result is a decimal. Schema posted - harryg