SQL Rails 通过关联加入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16115747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails joins through association
提问by spitfire109
In Ruby on Rails, I want to find employers in the city. Lets say the models are set up this way:
在 Ruby on Rails 中,我想在城市中找到雇主。假设模型是这样设置的:
City
has_many :suburbs
has_many :households, :through => suburbs
has_many :people, :through => suburbs
Suburb
has_many :households
has_many people, :through => households
belongs_to :city
Household
has_many :people
belongs_to :suburb
People
belongs_to :household
belongs_to :employer
Employer
has_many :people
I feel like I want some sort of Employer joins some_city.people but I don't know how to do this. If people belonged directly to cities, I could join Employer to people where city_id is something, but I want to find the same data without that direct join and I am a little lost.
我觉得我想要某种雇主加入 some_city.people 但我不知道该怎么做。如果人们直接属于城市,我可以将 Employer 加入到 city_id 是某种东西的人中,但是我想在没有直接加入的情况下找到相同的数据,我有点迷茫。
Thank you.
谢谢你。
采纳答案by Sean Hill
You can do the join like jvans has illustrated. Or you can setup your relationships like the following:
您可以像 jvans 所示进行连接。或者你可以像下面这样设置你的关系:
class Employer < ActiveRecord::Base
has_many :people
has_many :households, through: :people
has_many :suburbs, through: :households
has_many :cities, through: :suburbs
end
class Person < ActiveRecord::Base
belongs_to :household
belongs_to :employer
end
class Household < ActiveRecord::Base
belongs_to :suburb
has_many :people
end
class Suburb < ActiveRecord::Base
belongs_to :city
has_many :households
has_many :people, through: :households
end
class City < ActiveRecord::Base
has_many :suburbs
has_many :households, through: :suburbs
has_many :people, through: :households
has_many :employers, through: :people
end
Then you can join City
from Employer
, and vice-versa, directly.
然后您可以直接City
从加入Employer
,反之亦然。
For example:
例如:
Employer.joins(:cities).where("cities.name = ?", "Houston").first
SELECT "employers".* FROM "employers"
INNER JOIN "people" ON "people"."employer_id" = "employers"."id"
INNER JOIN "households" ON "households"."id" = "people"."household_id"
INNER JOIN "suburbs" ON "suburbs"."id" = "households"."suburb_id"
INNER JOIN "cities" ON "cities"."id" = "suburbs"."city_id" WHERE (cities.name = 'Houston')
LIMIT 1
回答by jvans
Use nested joins
使用嵌套连接
Employer.joins({:people => {:household => {:suburb => :city}}})
should give you the join table you're looking. If you were traversing the other direction you would use plural names
应该给你你正在寻找的连接表。如果您要穿越另一个方向,您将使用复数名称
City.joins( :suburbs => {:households => {:people => :employers }})