【发布时间】:2016-05-06 11:50:17
【问题描述】:
我正在开发一个游戏平台,我有以下(简化的)模型:
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 |
+---------+-----------+
我需要找到一种方法来确定 ID 为 39 和 41 的玩家在玩哪些游戏,在这种情况下,ID 为 10 和 13 的游戏。到目前为止我发现的查询是:
Game.joins(:players).where(players: {id: [39, 41]}).uniq
但是,此查询返回的是这些玩家中的任何一个玩过的游戏,而不是他们两个玩过的游戏。
【问题讨论】:
标签: mysql ruby-on-rails ruby activerecord