代码之家  ›  专栏  ›  技术社区  ›  cjm2671

我如何在菲尼克斯/埃克托聚集多个领域?

  •  1
  • cjm2671  · 技术社区  · 6 年前

    比如说我有关系:

    Posts has_many Comments
    

    我试着做一些如下的事情:

    Post |> Repo.aggregate(:count, :comments)
    

    然而,埃克托抱怨说:评论是一个虚拟的领域,因此它不能计算它。解决这个问题的好方法是什么?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Maarten van Vliet    6 年前

    我想你想要一组帖子的评论数。如果你想要所有帖子的评论数,你可以省略where子句。

    post_ids = [1, 2, 3]
    Comment
    |> where([c], c.post_id in ^post_ids)
    |> group_by([c], c.post_id)
    |> select([c], {c.post_id, count("*")})
    |> Repo.all()
    

    这将根据帖子ID对评论进行分组,并计算每个帖子的数量。它将返回一个包含元组的列表,例如

    [
      {1, 10},
      {2, 3},
      {3, 5}
    ]
    

    如果帖子没有评论,它将不会被列在结果集中。

        2
  •  0
  •   cjm2671    6 年前

    这是我的最终解决方案,在哪里 link has_many clicks

      def list_links_count do
    
        query = 
          from l in Link,
            join: c in Click, as: :click,
            where: c.link_id == l.id,
            group_by: l.id,
            select: {l, count(l.id)}
    
        query |> Repo.all
    
      end