簡體   English   中英

Ecto Elixir:預加載關聯中的總和值

[英]Ecto Elixir: Sum values in preloaded association

我有一個數據庫,其中有不同的歌曲,可以有多個請求,每個請求可以部分地具有多個投票。

我正在嘗試建立一個查詢,以獲取請求的所有信息(歌曲信息和用戶投票),但我只想選擇所需的重要信息。

我目前有這樣的設置

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

但這沒用...給出此錯誤消息

**(Ecto.QueryError)字段.Song.request中的.Song.request不是查詢中的關聯:

因此,我決定通過將選擇行更改為

  select: %{song: song, rating: sum(votes.rating)},

它只是說錯誤42803(grouping_error):列“ s0.id”必須出現在GROUP BY子句中或在聚合函數中使用

如何建立查詢以檢索請求並返回類似於get_requests_in_zone_with_votes中使用的結構的查詢?

謝謝您的時間。

計算子查詢中的總和,然后從主查詢中加入:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM