I have several types of content schemas which follow a similar pattern. They all belong to an Entity
schema.
Entity schemas have many Comment
s (as well as many-to-many relationships with Topic
s (via an EntityTopic
) join table.
I can preload a list of content like so:
def list(schema, order \\ [desc: :inserted_at]) do
from(s in schema,
order_by: ^order,
left_join: entity in assoc(s, :entity),
left_join: topics in assoc(entity, :topics),
left_join: comments in assoc(entity, :comments),
preload: [entity: {entity, topics: topics, comments: comments}]
)
|> Repo.all()
end
# Then to use it, Content.list(Article) or Content.list(Podcast), etc...
Similarly, I can preload just comment counts into entities by doing the following:
with_comment_counts =
from(e in Entity,
join: c in assoc(e, :comments),
group_by: e.id,
select_merge: %{id: e.id, comment_count: count(c.id)}
)
The question is, how can I change the first query so that it preloads entities and topics with the schema as before, but only loads the comment count and not the comments themselves?
I’ve tried several ways of arranging preload, select and select_merge statements but keep hitting errors revolving around the preload step or formatting the final select.