"Variable does not exist" 当我尝试使用 Ecto 进行查询时

"Variable does not exist" when I'm try to make a query with Ecto

我是 Elixir 的初学者,我正在尝试使用以下方法进行查询:

def posts_liked(%{id: id}, _info) do
  query = from u in Like, where: u.user_id == ^id
  {:ok, Repo.all(query)}
end

但是,假设变量 u 不存在。但是,in oficial doc 有相同的代码,其他手册也有。如何解决?

我的Like方案是:

schema "likes" do
  belongs_to :post, Myapp.Post, foreign_key: :post_id
  belongs_to :user, Myapp.User, foreign_key: :user_id

  timestamps()
end

我的猜测是您在本单元中遗漏了 import Ecto.Query。如果没有它,Ecto 认为 from 是一个普通函数,而不是宏,并开始检查参数是否有效。第一个参数是 u in Like,它脱糖为 Enum.member?(Like, u)Like 是一个有效值,但没有名为 u 的变量,Elixir 会抛出该错误。添加

import Ecto.Query

import Ecto.Query, only: [from: 2]

该模块将解决此问题。