PostgreSQL where all in array

后端 未结 9 1577
情书的邮戳
情书的邮戳 2020-11-30 07:23

What is the easiest and fastest way to achieve a clause where all elements in an array must be matched - not only one when using IN? After all it should behave

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 08:15

    Based on @Alex Blakemore's answer, the equivalent Rails 4 scope on you Conversation class would be:

    # Conversations exactly with users array
    scope :by_users, -> (users) { 
                               self.by_any_of_users(users)
                                 .group("conversations.id")
                                 .having("COUNT(*) = ?", users.length) -
                               joins(:conversations_users)
                                 .where("conversations_users.user_id NOT IN (?)", users)
    }
    # generates an IN clause
    scope :by_any_of_users, -> (users) { joins(:conversations_users).where(conversations_users: { user_id: users }).distinct }
    

    Note you can optimize it instead of doing a Rails - (minus) you could do a .where("NOT IN") but that would be really complex to read.

提交回复
热议问题