在关联列上使用 sum 时的 ArithmeticError
ArithmeticError when using sum on an associated column
我正在尝试将所有评分的总和添加到 post。但我收到一个错误:ArithmeticError: bad argument in arithmetic expression
。我相信那是因为并非所有 Post
都会有 ratings
与之关联。然后它将无法 sum
那些不存在的评级中的值。
如果数据库中没有与 post
关联的 ratings
,我该如何将评分设置为 0
?
查询:
from post in Post,
left_join: rating in assoc(post, :ratings),
group_by: post.id,
select: %{post | rating: sum(rating.value)}
架构:
schema "posts" do
field :rating, :integer, virtual: true
has_many :ratings, MyApp.Rating
end
schema "ratings" do
field :value, :integer
belongs_to :post, MyApp.Post
end
感谢 Elixir Slack 频道,我设法使用 postgres 函数解决了这个问题 coalesce()
。
The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.
有了这些新知识,我重写了我的查询,它似乎按预期工作:
from post in Post,
left_join: rating in assoc(post, :ratings),
group_by: post.id,
select: %{post | rating: sum(fragment("coalesce(?,0)", rating.value))}
Ecto
中还有一个coalesce功能
from post in Post,
left_join: rating in assoc(post, :ratings),
group_by: post.id,
select: %{post | rating: sum(coalesce(rating.value, 0))}
我正在尝试将所有评分的总和添加到 post。但我收到一个错误:ArithmeticError: bad argument in arithmetic expression
。我相信那是因为并非所有 Post
都会有 ratings
与之关联。然后它将无法 sum
那些不存在的评级中的值。
如果数据库中没有与 post
关联的 ratings
,我该如何将评分设置为 0
?
查询:
from post in Post,
left_join: rating in assoc(post, :ratings),
group_by: post.id,
select: %{post | rating: sum(rating.value)}
架构:
schema "posts" do
field :rating, :integer, virtual: true
has_many :ratings, MyApp.Rating
end
schema "ratings" do
field :value, :integer
belongs_to :post, MyApp.Post
end
感谢 Elixir Slack 频道,我设法使用 postgres 函数解决了这个问题 coalesce()
。
The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.
有了这些新知识,我重写了我的查询,它似乎按预期工作:
from post in Post,
left_join: rating in assoc(post, :ratings),
group_by: post.id,
select: %{post | rating: sum(fragment("coalesce(?,0)", rating.value))}
Ecto
中还有一个coalesce功能from post in Post,
left_join: rating in assoc(post, :ratings),
group_by: post.id,
select: %{post | rating: sum(coalesce(rating.value, 0))}