Ecto文档显示了如何根据模式中定义的关联连接2个表(A&lt; -B)。我想通过添加另一个表(B < - C)
来扩展它https://hexdocs.pm/ecto/Ecto.html#assoc/2
但是我收到了这个错误。我如何反映这样的事实:评论属于:此查询中的帖子?
Repo.all from u in App.User,
join: p in assoc(u, :posts),
join: c in assoc(p, :comments),
preload: [posts: p],
preload: [comments: c]
** (Ecto.QueryError) field `App.User.comments` in preload is not an association in query:
from u in App.User,
join: p in App.Post,
on: p.user_id == u.id,
join: c in App.Comment,
on: c.post_id == p.id,
select: u,
preload: [posts: p, comments: c]
(elixir) lib/enum.ex:651: Enum."-each/2-lists^foreach/1-0-"/2
(elixir) lib/enum.ex:651: Enum.each/2
(ecto) lib/ecto/repo/queryable.ex:119: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:40: Ecto.Repo.Queryable.all/4
答案 0 :(得分:1)
您可以在树状结构中预加载关联,然后根据需要映射结果。
> subquery = App.Post |> preload(:comments)
#Ecto.Query<from p in App.Post, preload: [:comments]>
> query = App.User |> preload(posts: ^subquery)
#Ecto.Query<from u in App.User,
preload: [posts: #Ecto.Query<from p in App.Post, preload: [:comments]>]>
> Repo.all(query)
[
%App.User{...},
%App.User{...},
%App.User{
...,
posts: [
%App.Post{...},
%App.Post{...},
%App.Post{
...,
comments: [
%App.Comment{...},
%App.Comment{...},
%App.Comment{...}
]
}
]
}
]