Rails/MySQL查询,其中第三级联接ID不';不存在
我有以下模型/关联:Rails/MySQL查询,其中第三级联接ID不';不存在,mysql,sql,ruby-on-rails,join,Mysql,Sql,Ruby On Rails,Join,我有以下模型/关联: class Property has_many :jobs end class Job belongs_to :property has_many :tasks end class Task belongs_to :job has_one :service end class Service belongs_to :task end 我正在尝试编写一个查询,其中返回的属性不包含包含ID数组中服务的任务的作业。因此: Property.join
class Property
has_many :jobs
end
class Job
belongs_to :property
has_many :tasks
end
class Task
belongs_to :job
has_one :service
end
class Service
belongs_to :task
end
我正在尝试编写一个查询,其中返回的属性不包含包含ID数组中服务的任务的作业。因此:
Property.joins(jobs: { tasks: :service }).where('services.id NOT IN (?)', params[:service_ids])
但它返回的基本上是任何属性,这些属性至少有一个作业,其中至少有一个任务没有这些服务ID
我试图让它返回的是那些没有任何工作的属性,这些属性包含这些服务的任务,但我不知道该怎么做
# Get all the job ids that have tasks with the services selected
job_ids = Job.joins( tasks: :service ).where(
"services.id IN (?)", params[:service_ids]
).select(:property_id).distinct
# Return only properties that do not have those jobs
properties = properties.where.not(id: job_ids)