我正在计划一个关系数据库来存储扑克游戏数据(比如将包含在牌局历史中的数据)。我想帮助弄清楚如何设计关联。似乎应该有 4 个模型:Game、Hand、Player 和 Action(给定玩家的单一 Action ,如加注、弃牌、跟注)。让我列出我所拥有的:
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
这有意义吗?
最佳答案
如果您打算使用 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
语句来确保您在使用它们时会遇到索引。如果您加载数百万条记录,表格扫描将非常痛苦,而且在这样的游戏中这不会花费很长时间,因为单手涉及数十个 Action ,而且通常每小时玩数十手。
关于sql - 德州扑克数据的关系数据库结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3692484/