简体   繁体   English

Rails左外连接

[英]Rails LEFT OUTER JOIN

Let's say i have the following models: 假设我有以下模型:

class Employee < ActiveRecord::Base
    has_many :shifts    
end

class Shift < ActiveRecord::Base
    belongs_to :employee
end

In my controller I want to load all employees including their shifts in a certain date range. 在我的控制器中,我想加载所有雇员,包括他们在特定日期范围内的班次。 But I also want to include employees without any shifts in that range. 但是我也想包括没有在此范围内任何变动的员工。

In my controller I tried: 在我的控制器中,我尝试:

@employees.joins("LEFT OUTER JOIN shifts ON employees.id = shifts.employee_id").where('shifts.starts_at BETWEEN ? and ?', weekBegin, weekEnd).to_json(:include => :shifts)

But this still just returns the employees with shifts in that date range. 但这仍然只是返回在该日期范围内轮班的员工。 I also want to return employees with no shifts in that date range. 我也想返回在该日期范围内没有班次的员工。

How does such a query work? 这样的查询如何工作?

You should include conditions on the shifts start time into the join statement: 您应将轮班开始时间的条件包括在join语句中:

@employees.joins("
     LEFT OUTER JOIN shifts 
     ON employees.id = shifts.employee_id
     AND shifts.starts_at 
         BETWEEN #{ActiveRecord::Base.sanitize(weekBegin)} 
             AND #{ActiveRecord::Base.sanitize(weekEnd)}
").to_json(:include => :shifts)

您可以尝试这样做

LEFT OUTER JOIN shifts ON employees.id = shifts.employee_id AND shifts.starts_at BETWEEN weekBegin and weekEnd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM