简体   繁体   English

带有子查询的Rails LEFT OUTER JOIN

[英]Rails LEFT OUTER JOIN with Subquery

I have a simple calendar application. 我有一个简单的日历应用程序。

Models: 楷模:

class Day < ActiveRecord::Base
  self.primary_key = "sdate"
  has_many :items, foreign_key: :sdate
end

class Item < ActiveRecord::Base
  belongs_to :day, :foreign_key => :sdate
  belongs_to :calendar
end

class Calendar < ActiveRecord::Base
  has_many :items
end

Requirements: Fetch ALL rows of days within a certain date range. 要求:提取特定日期范围内的所有天数。 Fetch associated rows of items with certain Calendar-IDs. 提取具有特定日历ID的相关项目行。

With SQL I could use the following query: 使用SQL,我可以使用以下查询:

SELECT * FROM days LEFT OUTER JOIN (
  SELECT * FROM items
  WHERE calendar_id IN (1, 4)
) AS items
ON days.sdate = items.sdate
WHERE days.sdate BETWEEN '2015-03-01' AND '2015-03-31';

I have tried several ways in Rails but I couldn't find a solution. 我在Rails中尝试了几种方法,但是找不到解决方案。

How can I do this in Rails 4? 如何在Rails 4中做到这一点? Eager loading would be great. 渴望加载将是巨大的。

Something along these lines: 遵循以下原则:

Day.joins('LEFT OUTER JOIN items ON days.sdate = items.sdate')
     .where('items.calendar_id IN (1, 4)')
     .where('days.sdate' => start_time..end_time)

http://guides.rubyonrails.org/active_record_querying.html http://guides.rubyonrails.org/active_record_querying.html

I was just trying to figure this out and I don't know of any way to do it with pure Rails. 我只是想弄清楚这一点,我不知道用纯Rails可以做到这一点。 But this will do what you want: 但这将满足您的要求:

Day.joins("LEFT OUTER JOIN (
  SELECT * FROM items
    WHERE calendar_id IN (1, 4)
  ) AS items
  ON days.sdate = items.sdate
  WHERE days.sdate BETWEEN '2015-03-01' AND '2015-03-31'");

I'm not using dates in the query in my code, so I'm not sure if you need the single quotes around the dates or not. 我没有在代码中的查询中使用日期,因此不确定是否需要在日期周围加上单引号。 But that is the syntax. 但这就是语法。 I think Left joins are very handy, I wish Rails had an actual LEFT JOIN method. 我认为左联接非常方便,我希望Rails拥有实际的LEFT JOIN方法。

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

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