我有以下两个模型:
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/