2016-05-06 54 views
2

我开发一个游戏平台,我有以下的(简化)型号:包含在ActiveRecord的查询所有ID

class Game < ActiveRecord:Base 
    has_many :game_players 
    has_many :players, through: :game_players 
end 

class Player < ActiveRecord:Base 
    has_many :game_players 
    has_many :games, through: :game_players 
end 

class GamePlayer < ActiveRecord:Base 
    belongs_to :game 
    belongs_to :player 
end 

我需要执行一个ActiveRecord查询,查找由某一群玩过的所有游戏用户。例如,给定数据:

+---------+-----------+ 
| game_id | player_id | 
+---------+-----------+ 
|  10 |  39 | 
|  10 |  41 | 
|  10 |  42 | 
|  12 |  41 | 
|  13 |  39 | 
|  13 |  41 | 
+---------+-----------+ 

我需要找到一种方法来确定哪些游戏是通过与IDS 39和41的球员,在这种情况下,将与IDS 10和13场比赛。我现在已经找到最多的查询是:

Game.joins(:players).where(players: {id: [39, 41]}).uniq 

然而,这个查询返回,而不是由他们两人玩的游戏由任何这些玩家玩的游戏。

回答

1

你可以给它一个尝试,如果你能执行两个查询,并相交的结果:

Game.joins(:players).where(players: {id: 39}) & Game.joins(:players).where(players: {id: 41}) 
+0

这是有效的,但是我想要执行一个单一的SQL查询,因为玩家的数量可以是任意大的 – Bustikiller

+0

'Game.joins(:players).where(players:{id:39})。where(players :{id:41})' - 尝试这样的事情 – dp7

1

此功能更像是一个SQL相交,并且应该给你,你在这种情况下,需要的结果:

Game.joins(:players).where(players: {id: [39,41]}).group('"games"."id"').having('COUNT("games"."id") > 1') 

真的,奇迹发生了,通过选择其中任一玩家玩游戏,然后通过game.id分组降低的结果,那些结果组中多个game.id。它从Rails控制台产生以下结果:

=> #<ActiveRecord::Relation [#<Game id: 10, created_at: "2016-05-07 01:17:25", updated_at: "2016-05-07 01:17:25">, #<Game id: 13, created_at: "2016-05-07 01:17:25", updated_at: "2016-05-07 01:17:25">]> 

请注意,此解决方案仅返回游戏10和13(基于样本数据)。手动验证表明,只有游戏10和13同时玩39和41玩家。

相关问题