Find all records which have a count of an association greater than zero

后端 未结 10 1586
北海茫月
北海茫月 2020-11-30 17:45

I\'m trying to do something that I thought it would be simple but it seems not to be.

I have a project model that has many vacancies.

class Project &         


        
相关标签:
10条回答
  • 2020-11-30 18:13
    # None
    Project.joins(:vacancies).group('projects.id').having('count(vacancies) = 0')
    # Any
    Project.joins(:vacancies).group('projects.id').having('count(vacancies) > 0')
    # One
    Project.joins(:vacancies).group('projects.id').having('count(vacancies) = 1')
    # More than 1
    Project.joins(:vacancies).group('projects.id').having('count(vacancies) > 1')
    
    0 讨论(0)
  • 2020-11-30 18:17

    In Rails 4+, you can also use includes or eager_load to get the same answer:

    Project.includes(:vacancies).references(:vacancies).
            where.not(vacancies: {id: nil})
    
    Project.eager_load(:vacancies).where.not(vacancies: {id: nil})
    
    0 讨论(0)
  • 2020-11-30 18:18

    You can also use EXISTS with SELECT 1 rather than selecting all the columns from the vacancies table:

    Project.where("EXISTS(SELECT 1 from vacancies where projects.id = vacancies.project_id)")
    
    0 讨论(0)
  • 2020-11-30 18:19

    Yeah, vacancies is not a field in the join. I believe you want:

    Project.joins(:vacancies).group("projects.id").having("count(vacancies.id)>0")
    
    0 讨论(0)
提交回复
热议问题