Phoenix/Ecto - 查询具有 nil 值的单个记录

Phoenix/Ecto - query for single record with a nil value

在我的 Phoenix 应用程序中,我想 运行 get_by() Ecto 查询单个记录 - 但是,我要搜索的字段之一应该计算为 nil,但 Phoenix/Ecto 禁止使用 nil 作为比较运算符。

这是我理想的(但失败了)查询:

target_record = Repo.get_by(Records, %{user_id: user_id, deleted_at: nil})

我已经能够在查询许多记录时使用 is_nil(field_name) 来查询 nil 字段,例如:

target_records = from(r in Records,
                        where: r.user_id == ^user_id,
                        where: is_nil(r.deleted_at))
                        |> Repo.all()

但是我不愿意将它用于我当前的任务,因为那将 return 一个列表...我的 Records table 可以有许多具有相同 user_id 但其中只有一个条目会有 deleted_at: nil,所以我不需要取回一个项目的列表,然后将其转换成地图...

我的意思是,我可以做到,但它看起来不太干净。

应该如何安排 get_by 查询才能包含 nil 值?

Repo.getRepo.get_by 非常适合非常简单的查询。但是,当您需要超越他们所能做的事情时,您将需要投入 Ecto.Query API。使用此 API 构建的查询可以与 Repo.oneRepo.one!Repo.all 一起使用。请注意,如果 Repo.one 获得超过 1 条记录,则会引发。

所以,这应该有效:

target_records = 
  from(r in Records, where: r.user_id == ^user_id and is_nil(r.deleted_at))
  |> Repo.one()

可以这样写:

target_records = 
  Repo.one from r in Records, where: r.user_id == ^user_id and is_nil(r.deleted_at)