Ecto Elixir:预加载关联中的和值

时间:2017-11-07 20:27:27

标签: mysql postgresql elixir phoenix-framework ecto

我有一个数据库,它有不同的歌曲,可以有多个请求,每个请求可以部分有多个投票。

我正在尝试构建一个查询来获取请求的所有信息(歌曲信息和用户投票),但我只想选择我需要的重要信息。

我目前已经设置了这样的

def get_requests_in_zone(zone_id, max_played) do
query = from request in Request,
  left_join: song in assoc(request, :song),
  where: request.zone_id == ^zone_id and request.times_played <= ^max_played,
  select: request,
  preload: [song: song],
  order_by:  [asc: request.times_played, desc: request.inserted_at]
Repo.all(query)
 end

def  calculate_rating(request_id)do
query = from votes in Vote,
  where: votes.request_id == ^request_id,
  select: sum(votes.rating)

Repo.one(query)
end

def get_requests_in_zone_with_votes(zone_id,max_played) do
Enum.map(get_requests_in_zone(zone_id,max_played),
  fn(x) ->
    %{title: x.song.title, url: x.song.url, thumbnail: x.song.thumbnail, rating: calculate_rating(x.id)} end)
end

但这会使多个查询计算每个请求的评级。我尝试构建一个查询,它类似于:

def get_requests_in_zone(zone_id, max_played) do
query = from song in Song,
  left_join: request in assoc(song, :requests),
  join: votes in assoc(request, :votes), 
where: request.zone_id == ^zone_id and request.times_played <= ^max_played,
  select: %{title: song.title, url: song.url, thumbnail: song.thumbnail, rating: sum(votes.rating)},
  preload: [requests: {request, votes: votes}],
  order_by:  [asc: request.times_played, desc: request.inserted_at]
Repo.all(query)
end

但它没有工作......给出了这个错误信息

preload中的

**(Ecto.QueryError)字段.Song.request不是查询中的关联:

所以我决定通过将选择线更改为

来在选择中添加完整的歌曲
  select: %{song: song, rating: sum(votes.rating)},

它只是说      错误42803(grouping_error):列&#34; s0.id&#34;必须出现在GROUP BY子句中或用于聚合函数

我如何构建一个检索请求并返回类似于get_requests_in_zone_with_votes中使用的结构的查询?

谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

计算子查询中的总和,并从主查询中加入:

q1 = from votes in Vote,
     group_by: votes.request_id,
     select: %{request_id: votes.request_id, total_rating: sum(votes.rating)}

q2 = from request in Request,
     left_join: song in assoc(request, :song),
     left_join: rating in subquery(q2), on: request.id == rating.request_id,
     where: request.zone_id == ^zone_id and request.times_played <= ^max_played,
     select: %{title: song.title, url: song.url, thumbnail: song.thumbnail, rating: rating.total_rating},
     order_by:  [asc: request.times_played, desc: request.inserted_at]