skw*_*eth 4 ecto phoenix-framework
在我的Phoenix应用程序中,我想get_by()对单个记录运行Ecto查询-但是,我要搜索的字段之一应评估为nil,但是Phoenix / Ecto禁止nil用作比较运算符。
这是我理想的(但失败的)查询:
target_record = Repo.get_by(Records, %{user_id: user_id, deleted_at: nil})
Run Code Online (Sandbox Code Playgroud)
我已经能够查询许多记录的查询中nil使用的字段is_nil(field_name),例如:
target_records = from(r in Records,
where: r.user_id == ^user_id,
where: is_nil(r.deleted_at))
|> Repo.all()
Run Code Online (Sandbox Code Playgroud)
但是我不愿意在当前任务中使用它,因为这将返回一个列表...我的Records表可以有很多相同的条目,user_id但是其中只有一个条目可以使用deleted_at: nil,所以我不需要找回一项的列表,然后将其转换为地图...
我的意思是,我可以做到,但看起来并不干净。
如何get_by安排查询,以便nil可以包含一个值?
的Repo.get和Repo.get_by非常简单的查询是巨大的。但是,当您需要超越他们的能力范围时,就需要使用Ecto.QueryAPI。查询构建与这个API搭配使用Repo.one,Repo.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()
Run Code Online (Sandbox Code Playgroud)
可以这样写:
target_records =
Repo.one from r in Records, where: r.user_id == ^user_id and is_nil(r.deleted_at)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2402 次 |
| 最近记录: |