我可以在 Ecto 中查询具有其中一个关联的总计数的模型吗?

Can I query a model with an aggregate count of one of it's association in Ecto?

是否可以编写一个查询,其中 returns 所有模型(即 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)

我试过使用 group_by 和 select(上图),但这只能部分奏效。查询结果排除了所有没有点赞的帖子。

如果这不可能,处理这个问题的最佳方法是什么?首先想到的是像这样映射查询结果:

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)

查询有两处错误:

  1. 您需要使用on而不是where来指定连接条件

  2. 如果您希望返回没有点赞的帖子,您需要使用 left_join 而不是 join

最终查询:

from p in Post, 
  left_join: l in Like, 
  on: l.post_id == p.id,
  group_by: p.id,
  select: {p, count(l.id)}

您也可以在 left_join 中使用 assoc 此处将自动添加正确的 on:

from p in Post, 
  left_join: l in assoc(p, :likes), 
  group_by: p.id,
  select: {p, count(l.id)}