elixir - 如何在不预加载的情况下加载关联?

标签 elixir ecto

我有以下两个模型:

schema "users" do
    field :email, :string
    field :crypted_password, :string
    field :password, :string, virtual: true

    has_many :exercise_entries, ExerciseEntry

    timestamps
end

和:
schema "exercise_entries" do
  field :date, Ecto.DateTime
  field :exercise, :string
  field :category, :string
  field :weight, :float
  field :reps, :integer
  belongs_to :user, User

  timestamps
end

我在 iex 中运行了以下代码:
u = Repo.get(User, 1)
iex(8)> u.exercise_entries
#Ecto.Association.NotLoaded<association :exercise_entries is not loaded>

我知道我可以做 Repo.get(User,1) |> Repo.preload([:exercise_entries])然后我可以访问运动条目。是否有可能以某种方式加载运动条目而不先预加载它们?

最佳答案

Ecto 需要执行另一个数据库查询来获取练习条目。会正常的Repo.all查询,而不是手动构建它,您可以使用 Ecto.assoc

ee = Repo.all(Ecto.assoc(u, :exercise_entries))

关于elixir - 如何在不预加载的情况下加载关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34864508/

相关文章:

database - 尝试删除结构时出现 Ecto 约束错误

elixir - 无法删除模型——函数 Ecto.Query.__changeset__/0 未定义或私有(private)

ubuntu - 在 Ubuntu 17.04 Zesty 上安装 Elixir 失败

testing - Phoenix 丹药 : mock internal functions

elixir - Ecto 变更集和 Dialyzer 错误

elixir - 在 Phoenix 应用程序中为异常设置自定义响应

elixir 已安装但 iex 命令错误

Elixir 匿名函数、捕获和部分应用程序

elixir - 为什么 Elixir 的 nil 实现了 Access 行为?

performance - 为什么 Elixir 中大量电量超时?