是否有可能组成一个返回所有模型(即Post)的查询,其总计数为其中一个关联(即Like).
Repo.all(from p in Post,
join: l in Like,
where l.post_id == p.id,
group_by: p.id,
select: {p, count(l.id)
Run Code Online (Sandbox Code Playgroud)
我尝试过使用group_by并选择(上面),但这只是部分有效.查询的结果会排除所有没有任何喜欢的帖子.
如果这不可能,那么处理这个问题的最佳方法是什么?首先想到的是映射查询结果,如:
posts =
Repo.all Post
|> Enum.map(fn(post) ->
likes_query = from l in Like, where: l.post_id == ^post.id
likes_count = Repo.aggregate(likes_query, :count, :id)
%{post: post, likes_count: likes_count}
end)
Run Code Online (Sandbox Code Playgroud)