我有一个具有以下模型的 Rails 应用程序:
class Partner < ActiveRecord::Base
has_many :timesheets
has_many :timeslots, through: :timesheets
# ...
end
class Timeslot < ActiveRecord::Base
has_many :timesheets
has_many :partners, through: :timesheets
# ...
end
class Timesheet < ActiveRecord::Base
belongs_to :partner
belongs_to :timeslot
# ...
end
请注意时间表如何充当用于存储合作伙伴-时间段对的排序连接表。我想获得所有此类时隙满足某些条件的合作伙伴-时隙对。我实际上根本不关心此查询的 Timesheet 对象。我发现合适的 SQL 是这样的:
SELECT partners.*, timeslots.*
FROM timesheets
JOIN partners
ON timesheets.partner_id = partners.id
JOIN timeslots
ON timesheets.timeslot_id = timeslots.id
WHERE (...some condition logic that I can figure out on my own...)
请注意,虽然我正在查询时间表表,但实际上我只需要 Partner 和 Timeslot 对象。
你能用 Rails 做到这一点吗?
有更好的方法吗?
杂项信息:
我正在使用 MySQL 作为数据库
最佳答案
是的,您当然可以在 Rails 中做到这一点。你可以从:
partner_timeslots = Partner.joins([ timesheets: :timeslot ]).select('partners.*, timeslots.*')
这将生成以下查询:
select partners.*, timeslots.*
from partners
inner join timesheets on timesheets.partner_id = partners.id
inner join timeslots on timeslots.id = timesheets.timeslot_id
如果在控制台上尝试,请尝试 partner_timeslots.to_yaml
以查看返回的所有 partners
和 timeslots
属性。
关于mysql - 连接表上的 Rails SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34889918/