我正在开发一个游戏平台,我有以下(简化的)模型:
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 |
+---------+-----------+我需要找到一种方法来确定in为39和41的玩家玩的是哪些游戏,在本例中,将是in为10和13的游戏。到目前为止,我找到的查询是:
Game.joins(:players).where(players: {id: [39, 41]}).uniq但是,此查询返回的是这些玩家中的任何一个玩的游戏,而不是他们两个玩的游戏。
发布于 2016-05-06 20:19:27
如果您可以执行两个查询并将结果相交,则可以尝试一下:
Game.joins(:players).where(players: {id: 39}) & Game.joins(:players).where(players: {id: 41}) 发布于 2016-05-07 09:52:04
它的功能更像SQL INTERSECT,应该会给出本例中所需的结果:
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在玩。
https://stackoverflow.com/questions/37071651
复制相似问题