我正在计划一个关系数据库来存储扑克游戏数据(就像手册中包含的内容一样)。我想帮助弄清楚如何设计关联。看起来应该有4种模式:游戏,手牌,玩家和动作(给定玩家的单动,如加注,弃牌,跟注)。让我列出我所拥有的:
class Game < ActiveRecord::Base
has_many :hands
has_many :actions
has_and_belongs_to_many :players
end
class Hand < ActiveRecord::Base
has_many :actions
belongs_to :game
has_and_belongs_to_many :players
end
class Action < ActiveRecord::Base
belongs_to :game
belongs_to :hand
belongs_to :player
end
class Player < ActiveRecord::Base
has_and_belongs_to_many :games
has_and_belongs_to_many :hands
has_many :actions
end
这有意义吗?
答案 0 :(得分:1)
作为初稿有道理。由您提供的关联产生以下表格和关键字:
Game :: Game_id (PK);....
Hand :: Hand_id (PK); Game_id (FK);....
Player :: Player_id (PK); Action_id (FK);
ActionType :: ActionType_id (PK); Type;
(Note this table will only have three records - raise, fold, call)
Action :: Action_id (PK); ActionType_id (FK); Game_id (FK); Hand_id (FK); Player_id (FK);....
PlayerHand :: Player_id (FK); Hand_id (FK); Has_or_Belongs; (PK is (Player_id, Hand_id))
GamePlayer :: Game_id (FK); Player_id (FK); Has_or_Belongs; (PK is (Game_id, Player_id))
答案 1 :(得分:1)
如果您计划使用has_and_belongs_to_many
,则应该切换到使用has_many ..., :through
,因为它更容易管理。您已经拥有了一个Action模型,可以满足您的需求,而无需创建一些连接表:
class Game < ActiveRecord::Base
has_many :hands
end
class Hand < ActiveRecord::Base
has_many :actions
belongs_to :game
has_many :players,
:through => :actions,
:source => :player
end
class Action < ActiveRecord::Base
belongs_to :game
belongs_to :hand
belongs_to :player
end
class Player < ActiveRecord::Base
has_many :actions
has_many :played_games,
:through => :actions,
:as => :game
has_many :played_hands,
:through => :actions,
:as => :hand
end
通常,查询中涉及的表越少,运行的速度就越快。涉及任何类型的JOIN
将导致不可预测的查询性能。
请务必仔细索引表,并使用EXAMINE
语句确保在使用索引时遇到索引。如果你用数百万条记录加载表扫描会非常痛苦,而且在这样的游戏中不会花费很长时间,因为单手涉及数十个动作,而且每小时玩几十手就很常见。