我有以下两个模型:
schema "users" do
field :email, :string
field :crypted_password, :string
field :password, :string, virtual: true
has_many :exercise_entries, ExerciseEntry
timestamps
end
Run Code Online (Sandbox Code Playgroud)
和:
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
Run Code Online (Sandbox Code Playgroud)
我在 iex 中运行了以下代码:
u = Repo.get(User, 1)
iex(8)> u.exercise_entries
#Ecto.Association.NotLoaded<association :exercise_entries is not loaded>
Run Code Online (Sandbox Code Playgroud)
我知道我可以做Repo.get(User,1) |> Repo.preload([:exercise_entries]),然后我可以访问锻炼条目。是否有可能以某种方式加载运动条目而不先预加载它们?
Ecto 需要执行另一个数据库查询来获取练习条目。这将是正常的Repo.all查询,但您可以使用而不是手动构建它Ecto.assoc
ee = Repo.all(Ecto.assoc(u, :exercise_entries))
Run Code Online (Sandbox Code Playgroud)