gpt4 book ai didi

mysql - Rails/MySQL 查询,其中第三级连接 ID 不存在

转载 作者:行者123 更新时间:2023-11-29 18:58:17 25 4
gpt4 key购买 nike

我有以下模型/协会:

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)

关于mysql - Rails/MySQL 查询,其中第三级连接 ID 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com