为什么我在此Ecto查询中收到未绑定的可变消息?

时间:2018-08-23 04:31:58

标签: elixir ecto phoenix elixir-framework

嘿,我正在尝试查询,我的代码如下:

  def show(conn, _params) do
user = Guardian.Plug.current_resource(conn)
team = Web.get_team!(user.team.id)

score_query =
  from(
    u in User,
    where: u.team.id == team.id,
    select: sum(u.score)
  )

team_score = Repo.all(score_query)

IO.puts("score")
IO.inspect(team_score)

conn |> render("team.json", team: team)

当我尝试运行它时,出现一条错误消息:

** (Ecto.Query.CompileError) unbound variable `team` in query

但是为什么不绑定呢? 我该如何解决它,为什么会发生?

1 个答案:

答案 0 :(得分:4)

您应该pin (^) team.id

score_query =
  from(
    u in User,
    #                   ⇓ HERE
    where: u.team.id == ^team.id,
    select: sum(u.score)
  )

根据Ecto.Query documentation

  

可以使用^将外部值和Elixir表达式注入查询表达式中:

def with_minimum(age, height_ft) do
  from u in "users",
    where: u.age > ^age and u.height > ^(height_ft * 3.28),
    select: u.name
end