gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:15:44 26 4
gpt4 key购买 nike

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

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

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

我已经能够在查询许多记录时使用 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()

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

我的意思是,我可以这样做,但它似乎不是很干净。

应该如何安排 get_by 查询,以便可以包含 nil 值?

最佳答案

Repo.getRepo.get_by非常适合非常简单的查询。但是,当您需要超出他们的能力范围时,您需要访问 Ecto.Query API。使用此 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()

并且可以写成:
target_records = 
Repo.one from r in Records, where: r.user_id == ^user_id and is_nil(r.deleted_at)

关于phoenix-framework - Phoenix/Ecto - 查询具有 nil 值的单个记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com