PostgreSQL where all in array

后端 未结 9 1583
情书的邮戳
情书的邮戳 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:17

    This preserves ActiveRecord objects.

    In the below example, I want to know the time sheets which are associated with all codes in the array.

    codes = [8,9]
    
    Timesheet.joins(:codes).select('count(*) as count, timesheets.*').
               where('codes.id': codes).
               group('timesheets.id').
               having('count(*) = ?', codes.length)
    

    You should have the full ActiveRecord objects to work with. If you want it to be a true scope, you can just use your above example and pass in the results with .pluck(:id).

提交回复
热议问题