【发布时间】:2012-06-25 21:55:41
【问题描述】:
这是我得到的:
我有一个模型比赛和一个模型团队。一场比赛有 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,我会在只需要一次查询的情况下查询数据库两次。
【问题讨论】:
标签: sql ruby-on-rails activerecord has-many belongs-to