elixir - 如何在 Repo.one 中使用 Repo.get 和 select like

标签 elixir phoenix-framework ecto

我不确定这是否可行,但我喜欢 Repo.get 返回 Struct 的事实。

我正在尝试执行以下操作:

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)我得到了一个方便的用户结构。但是这个查询从我试图过滤的数据库中返回用户的所有信息(例如,我不想在我的 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)
这将返回一个基于 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.



因此,返回的结构将具有模型/模式中描述的所有字段,但我们不选择它们的值为 nil。

关于elixir - 如何在 Repo.one 中使用 Repo.get 和 select like,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40831141/

相关文章:

erlang - 如何确保任何机器上的时间戳都是UTC时间

spring-boot - 了解 Elixir

elixir - 在 umbrella 应用程序中运行 mix ecto seeds 文件

elixir - ecto add/3 默认无法正常工作

postgresql - 如何断开 Postgrex 连接?

phoenix-framework - Phoenix 框架中的永久 cookie

elixir - 如何将 erlang 包添加到 elixir 应用程序中

elixir - 如何验证 Phoenix 框架中的存在?

elixir - 在由OR连接的where子句中组成具有多个列的Ecto查询

unit-testing - 是否可以在 ExUnit 测试中 stub (模拟?)Ecto.UUID.generate?