如何像 Repo.one 一样将 Repo.get 与 select 一起使用
How to use Repo.get with select like in Repo.one
我不确定这是否可行,但我喜欢 Repo.get 是 return 结构这一事实。
我正在尝试做类似的事情:
Repo.get(User, id, select: [:id, :name])
点赞:
Repo.one(from u in User, where: u.id == ^id, select: [u.id, u.name]
但是对于 Repo.get,我无法从 Ecto 文档中弄清楚是否可行以及如何实现。
上下文:我正在使用 Guardian 并且序列化程序执行如下操作:
def from_token("User:" <> id), do: {:ok, Repo.get(User, id,)}
所以当我调用 current_resource(conn)
时,我得到了一个方便的用户结构。但是这个查询 return 我试图过滤的数据库中用户的所有信息(例如,我不想在我的 current_resource(conn)
.
中使用加密密码
正如@Dogbert 在评论中提到的那样,解决方案是:
import Ecto.Query
from(User) |> select([:id, :name]) |> Repo.get(id)
在监护人序列化程序中:
import Ecto.Query
....
def from_token("User:" <> id), do: {:ok, from(User) |> select([:id, :name]) |> Repo.get(id)}
.....
来自 Ecto.Repo 文档:
get(queryable, id, opts)
get(queryable :: Ecto.Queryable.t, id :: term, opts :: Keyword.t) ::
Ecto.Schema.t |
nil |
no_return
Fetches a single struct from the data store where the primary key matches the given id.
Returns nil if no result was found. If the struct in the queryable has no or more than one primary key, it will raise an argument error.
如前所述,get/3
正在等待的第一个参数是可查询的。这就是为什么我们可以用 from(User) |> select([:id, :name])
构造可查询对象,然后将其传递给 Repo.get(id)
这将 return 一个基于 user
模型的结构。
正如 phoenix-framework docs 提到的:
Each model defines the fields of our schema as well as their types.
They each define a struct with the same fields in our schema.
因此,returned 的结构将具有 model/schema 中描述的所有字段,但在我们不 select 的情况下具有 nil 值。
我不确定这是否可行,但我喜欢 Repo.get 是 return 结构这一事实。
我正在尝试做类似的事情:
Repo.get(User, id, select: [:id, :name])
点赞:
Repo.one(from u in User, where: u.id == ^id, select: [u.id, u.name]
但是对于 Repo.get,我无法从 Ecto 文档中弄清楚是否可行以及如何实现。
上下文:我正在使用 Guardian 并且序列化程序执行如下操作:
def from_token("User:" <> id), do: {:ok, Repo.get(User, id,)}
所以当我调用 current_resource(conn)
时,我得到了一个方便的用户结构。但是这个查询 return 我试图过滤的数据库中用户的所有信息(例如,我不想在我的 current_resource(conn)
.
正如@Dogbert 在评论中提到的那样,解决方案是:
import Ecto.Query
from(User) |> select([:id, :name]) |> Repo.get(id)
在监护人序列化程序中:
import Ecto.Query
....
def from_token("User:" <> id), do: {:ok, from(User) |> select([:id, :name]) |> Repo.get(id)}
.....
来自 Ecto.Repo 文档:
get(queryable, id, opts) get(queryable :: Ecto.Queryable.t, id :: term, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return
Fetches a single struct from the data store where the primary key matches the given id.
Returns nil if no result was found. If the struct in the queryable has no or more than one primary key, it will raise an argument error.
如前所述,get/3
正在等待的第一个参数是可查询的。这就是为什么我们可以用 from(User) |> select([:id, :name])
构造可查询对象,然后将其传递给 Repo.get(id)
这将 return 一个基于 user
模型的结构。
正如 phoenix-framework docs 提到的:
Each model defines the fields of our schema as well as their types. They each define a struct with the same fields in our schema.
因此,returned 的结构将具有 model/schema 中描述的所有字段,但在我们不 select 的情况下具有 nil 值。