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

标签 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.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/

相关文章:

ruby-on-rails - 为什么 Ruby "script/generate"返回 "No such file or directory"?

c# - mysql外部访问

mysql - 在 phpMyAdmin 中创建函数 - 错误 : access denied you need the super privilege for this operation

mysql - Errno 121,写入或更新时重复键?

MYSQL 内部选择查询

c# - 使用 foreach 循环将不同类型的列表插入到 SQL Server 数据库中

mysql - 为什么 MySQL 自动增量会在插入失败时增加?

mysql - 将一个表的项目搜索到另一个表中保存结果

ruby-on-rails - 链接到 ruby​​ 中的表单

javascript - 使用 .js.erb