0

对不起,如果问题的标题没有任何意义,我仍然是初学者,我只是不知道如何解释它。

这是我当前运行良好的 SQL 查询

select teams.id as team_id, teams.team_name, players.type_name, sum(points) as points
from teams 
inner join gameweeks on teams.id = gameweeks.team_id    
inner join gameweeks_players on gameweeks.id = gameweeks_players.gameweek_id
inner join players on gameweeks_players.player_id = players.id
inner join player_fixtures on players.id = player_fixtures.player_id AND player_fixtures.gw_number = gameweeks.number
group by teams.id, players.type_name

在 Rails 中,我将此查询翻译成

Team.joins(gameweeks: :players).
joins("inner join player_fixtures on players.id = player_fixtures.player_id AND player_fixtures.gw_number = gameweeks.number").
group("teams.id, players.type_name").
select("teams.id, teams.team_name, players.type_name as type, sum(points) as points")

在 Rails 中,我有这两个模型。

class League < ActiveRecord::Base
    belongs_to :user
    has_many :league_teams
    has_many :teams, :through => :league_teams
end

class Team < ActiveRecord::Base
    has_many :gameweeks
    has_many :league_teams
    has_many :leagues, :through => :league_teams
end

我想将我的查询修改为仅与联赛关联的球队(我想以某种方式传递该联赛的 ID)

我只是不知道该怎么做,而且我缺少用正确的关键字在谷歌上搜索它的知识......

你能指出我正确的方向吗?

4

1 回答 1

1

本指南应该能够为您指明正确的方向: http: //guides.rubyonrails.org/active_record_querying.html#conditions

我无法测试这是否有效,但你可以尝试这样的事情:

League.Team.select("teams.id, teams.team_name, players.type_name as type, sum(points) AS points")
           .joins(gameweeks: :players)
           .joins("INNER JOIN player_fixtures ON players.id = player_fixtures.player_id AND player_fixtures.gw_number = gameweeks.number")
           .where("league.id = ?", leagueId)
           .group("teams.id, players.type_name")

编辑:将问题评论中的@gregates 答案与我的合并。

于 2013-09-04T20:41:59.943 回答