elixir - Ecto table join -
the ecto documentation shows how join 2 tables (a<-b) based on association defined in schema. i'd expand adding table (b <- c)
https://hexdocs.pm/ecto/ecto.html#assoc/2
but error. how reflect fact :comments belong :posts in query?
repo.all 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 not association in query: 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
you can preload associations in tree-like structure , map results needed.
> 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{...} ] } ] } ]
Comments
Post a Comment