Child 回到 parent 的关联未加载

Child association back to parent is not loaded

我有两个模型与 has_many 和 belongs_to 相关联。 使用 Repo.preload 加载工作正常,但我注意到 child 没有返回到 parent 的关联 -- 看到 Ecto.Association.NotLoaded.

我是否也必须将 child 关联预加载回 parent? 有没有办法将两个关联从 parent 预加载调用链接起来?

(我使用的是 Ecto 2.0 rc5。)

Do I have to preload the child association back to the parent as well? Is there a way to have the both association linked up from the parent preload call?

由于 Elixir 映射(以及结构)是不可变的,因此其中不可能有循环,这就是您需要从 child 返回其 parent 的引用。

我通常解决这个问题的方法是将 parent 与 child 一起显式传递给需要访问两者的任何函数,或者预加载更多级别的关联(但这如果您已经在某处加载了 parent 关联,则此方法会浪费内存):

Repo.get(Post, 1) |> Repo.preload([comments: [:post]])

这将使 Post 的所有评论都嵌入了 Post 的副本(但这些帖子不会有 他们的 评论已加载)。