[英]Rails LEFT OUTER JOIN
假设我有以下模型:
class Employee < ActiveRecord::Base
has_many :shifts
end
class Shift < ActiveRecord::Base
belongs_to :employee
end
在我的控制器中,我想加载所有雇员,包括他们在特定日期范围内的班次。 但是我也想包括没有在此范围内任何变动的员工。
在我的控制器中,我尝试:
@employees.joins("LEFT OUTER JOIN shifts ON employees.id = shifts.employee_id").where('shifts.starts_at BETWEEN ? and ?', weekBegin, weekEnd).to_json(:include => :shifts)
但这仍然只是返回在该日期范围内轮班的员工。 我也想返回在该日期范围内没有班次的员工。
这样的查询如何工作?
您应将轮班开始时间的条件包括在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.