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

Why Am I Getting An Unbound Variable Message On This Ecto Query?

嘿,我正在尝试进行查询,我的代码如下所示:

  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

但为什么是未绑定的? 我该如何解决它,为什么会这样?

你应该pin (^) team.id:

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

根据Ecto.Query documentation

External values and Elixir expressions can be injected into a query expression with ^:

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