关系
第二组关系是最合适的。正如 Mik_Die 所提到的,主要原因是它被规范化了。如果您要查看第一个示例的 DB 架构,您会得到类似以下的内容
Restaurant (belongs_to) -> Neighborhood
Restaurant (belongs_to) -> City
Table: Restaurant
Column | Type |
---------------------------------------------
ID | Integer | Primary Key
name | String |
neighborhood_id | Integer | Foreign Key
city_id* | Integer | Foreign Key
Table: Neighborhood
Column | Type |
---------------------------------------------
ID | Integer | Primary Key
name | String |
city_id* | Integer | Foreign Key
Table: City
Column | Type |
---------------------------------------------
ID | Integer | Primary Key
name | String |
如果您查看我在旁边加上星号的列,您会发现它在两个不同的表中重复,这是您在规范化数据库时要避免的。
第二个模式将几乎相同。您只需从 Restaurant 中删除 city_id 列。
Restaurant (belongs_to) -> Neighborhood
Neighborhood (belongs_to) -> City
Table: Restaurant
Column | Type |
---------------------------------------------
ID | Integer | Primary Key
name | String |
neighborhood_id | Integer | Foreign Key
Rails 的用武之地
您的帖子被标记为 Ruby on Rails,因此我认为讨论 Rails 如何看待这种关系很重要。您熟悉 belongs_to 和 has_many 关联。 Rails 通过:through 选项为has_many 提供了出色的扩展。
我假设您有兴趣将 City 存储在 Restaurant 表中,因为您希望能够找到属于整个城市的所有餐厅。 has_many 的 :through 选项允许该功能。
你的模型看起来像这样
class Restaurant < ActiveRecord::Base
belongs_to :neighborhood
end
class Neighborhood < ActiveRecord::Base
has_many :restaurants
belongs_to :city
end
class City < ActiveRecord::Base
has_many :neighborhoods
has_many :restaurants, through: :neighborhoods
end
然后你可以做这样的事情
@neighborhood.restaurants # => Returns all restaurants for that neighborhood
@city.restaurants # => Returns all restaurants from each of the neighborhoods belonging to the city