I have the following schemata:
schema "posts" do
field :body, :string
has_many :comments, Comment
end
schema "comments" do
field :message, :string
belongs_to :post, Post
has_many :tag, Tag
end
schema "tags" do
field :tag, :string
belongs_to :comment, Comment
end
I want to select all posts, an arbitrary comment for each post, and the tags for each comment. I initially tried using preload
in a subquery.
Repo.all(
from post in Posts,
as: :post,
left_lateral_join: arbitrary_comment in subquery(
from comment in Comment,
where: comment.post_id == parent_as(:post).id,
left_join: tag in assoc(comment, :tags),
preload: [tags: tag],
limit: 1),
on: true,
select: %{post: post, arbitrary_comment: arbitrary_comment}
)
but this returned an error since preloading isnât allowed in subqueries. I also tried
Repo.all(
from post in Posts,
as: :post,
left_lateral_join: arbitrary_comment in subquery(
from comment in Comment,
where: comment.post_id == parent_as(:post).id,
left_join: tag in assoc(comment, :tags),
select: %Comment{comment | tags: tag}),
limit: 1),
on: true,
select: %{post: post, arbitrary_comment: arbitrary_comment}
)
but this only returned one tag for each comment.
I donât want to use the hack of putting arbitrary_comment
in the comments
association, because what if e.g. I want to return two comments, like the most recent comment and the most popular comment.