这是我所拥有的:
我有一个模型比赛和一个模型团队。一场比赛有 home_team 和 away_team。事实上,这是一个 2:n 的关系。
class Team < ActiveRecord::Base
has_many :home_matches, :class_name => 'Match', :foreign_key => 'home_team_id'
has_many :away_matches, :class_name => 'Match', :foreign_key => 'away_team_id'
public
def matches
return home_matches + away_matches
end
end
和
class Match < ActiveRecord::Base
attr_accessible :away_team_id, :home_team_id
belongs_to :home_team, :class_name => 'Team', :foreign_key => 'home_team_id'
belongs_to :away_team, :class_name => 'Team', :foreign_key => 'away_team_id'
结尾
实际上,我现在可以调用 Team.find(2).matches 并获得所有客场和主场比赛。但我不喜欢的是它需要两个 SQL 查询而不是一个:
SELECT `matches`.* FROM `matches` WHERE `matches`.`home_team_id` = 2
SELECT `matches`.* FROM `matches` WHERE `matches`.`away_team_id` = 2
我怎样才能让 Rails 使用这个查询?
SELECT `matches`.* FROM `matches` WHERE `matches`.`home_team_id` = 2 OR `matches`.`away_team_id` = 2
反过来也会引起同样的头痛。如果我定义了一个team
合并的方法,home_team
并且away_team
我在只需要一个查询的情况下查询数据库两次。