【发布时间】:2017-12-21 11:43:34
【问题描述】:
我在 Ecto 中有一个查询,包括包含整数的列的总和。我使用 MySQL 作为数据库。
例如
result = Repo.one(
from v in Vote,
where: [post_id: 1],
select: sum(v.direction)
)
IO.inspect(result)
# Yields: #Decimal<5>
结果从 Ecto 返回为 #Decimal<x>。当我将其编码为 json 时,它会转换为字符串。理想情况下,我希望它是一个整数,特别是因为结果将始终是数据库中的一个整数。
投射这个的最佳方式是什么?
这是我的架构:
schema "votes" do
field :direction, :integer
belongs_to :user, Linklet.User
belongs_to :link, Linklet.Link
timestamps()
end
我已经设法通过在片段中使用 MySQL 的 CONVERT 函数来实现预期的结果,但这似乎不是最可靠的方法:
result = Repo.one(
from v in Vote,
where: [post_id: 1],
select: fragment("CONVERT(?, SIGNED)", sum(v.direction))
)
有没有更好的办法?
【问题讨论】:
-
如果你希望它是整数,为什么不首先将它作为整数存储在数据库中呢?另外,请显示
Vote的架构文件。 -
Decimal.to_integer(result)? -
@mudasobwa
direction列是一个整数。我不确定为什么结果是小数。架构已发布 -
@Dogbert 理想情况下,我希望在查询时进行类型转换以避免映射结果。
-
是的,它也在迁移中声明为整数。我检查了数据库本身,它是一个整数。也许这是一个mysql的东西......