【问题标题】:Query that finds objects with ALL association ids (Rails 4)查找具有所有关联 ID 的对象的查询 (Rails 4)
【发布时间】:2014-01-31 09:58:26
【问题描述】:

背景:通过 CommunityPosts,帖子有许多社区。我了解以下查询返回与这些 community_id 中的任何一个相关联的帖子。

Post.joins(:communities).where(communities: { id: [1,2,3] })

目标:我想查询与数组中所有三个 community_id 相关的帖子。将社区 1、2 和 3 作为关联的帖子

编辑:请假设数组的长度是未知的。将此数组用于说明目的。

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-4


    【解决方案1】:

    试试这个,

    ids=[...]
    Post.joins(:communities).select(“count(communities.id) AS cnt”).where(id: ids).group(‘post.id’).having(cnt: ids.size)
    

    【讨论】:

      【解决方案2】:
      ids = [1, 2, 3] # and etc
      Post.joins(:communities).where("communities.id IN ?", ids)
      

      希望它有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-04
        • 1970-01-01
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-29
        相关资源
        最近更新 更多