简体   繁体   English

使用Rails中的联接表的模型进行左外部联接

[英]Left outer join using the model of the joined table in rails

I need to do a left outer join in rails, but I need the model objects to be for the joined table. 我需要在rails中进行左外部联接,但是我需要模型对象用于联接表。

What I want is a list of the days, with the metrics for each day. 我想要的是日期列表,以及每天的指标。 I need to have all days regardless of whether or not there were metrics, but I don't want to make a bunch of round trips to the database. 无论是否有指标,我都需要整天工作,但我不想往返于数据库。

This works, but causes problems because it thinks I have PeriodDay objects when I really want Metric objects: 这可行,但是会引起问题,因为当我真的想要Metric对象时,它认为我有PeriodDay对象:

PeriodDay.select("metrics.*").join('LEFT OUTER JOIN metrics ON period_days.date = metrics.date').where('period_id = ?', current_period)

I can use find_by_sql on the Metric object, but the query building is more complicated (and conditional) than this simplified example, so I would rather figure out the "rails way" for this problem. 我可以在Metric对象上使用find_by_sql,但是查询构建比此简化示例更加复杂(且有条件),因此我宁愿找出解决此问题的“方法”。

My current workaround is to loop through the records and create Metric objects from the attributes of the PeriodDay object. 我当前的解决方法是遍历记录并从PeriodDay对象的属性创建Metric对象。 It doesn't feel efficient, but it is better than making multiple database calls. 感觉效率不高,但是比进行多个数据库调用要好。

metrics = []
recs = PeriodDay.select("metrics.*").join('LEFT OUTER JOIN metrics ON period_days.date = metrics.date').where('period_id = ?', current_period)
for rec in recs
  metrics << Metric.new(rec.attributes)
end

Assuming that Period has many PeriodDay has many Metric, and that period_id is an attribute of your PeriodDay model, your workaround should be identical to something like this: 假设Period有许多PeriodDay有很多Metric,并且period_id是PeriodDay模型的属性,则解决方法应与以下类似:

Metric.includes(:period_day).where(:period_day => {:period_id => @current_period})

This doesn't get you a list of days with their respective Metric objects as you mentioned in the original question, but it gets you a list of all Metric objects for a particular period. 正如您在原始问题中提到的那样,这不会为您提供包含其各自的Metric对象的日期列表,但会为您提供特定时间段内所有Metric对象的列表。 (unless I'm missing something...) (除非我想念什么...)

If you want a list of PeriodDay objects with their included Metric objects, you can use includes instead of joins . 如果要获取PeriodDay对象及其包含的Metric对象的列表,可以使用includes而不是joins

PeriodDay.includes(:metrics).where(:period_id => @current_period)

This will execute two queries (one to get period days and the other to get metrics) but it is a lot more readable. 这将执行两个查询(一个查询获取期间天,另一个查询获取指标),但可读性更高。

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

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