0

我正在编写一个小游戏,需要一个代表玩家和比赛的数据库。

玩家有名字、玩家ID和等级。一场比赛有一个 ID 和两个玩家。

播放器

  • id(大整数)
  • 名称(字符串)
  • 玩家ID(字符串)
  • 排名(整数)

匹配

  • id(大整数)
  • 匹配ID(字符串)
  • playerOne(玩家)
  • playerTwo(玩家)

最终,我想在 Player 中有一个“匹配”关系,但我不明白的一点是如何让一个实体有两个相同类型的实体,我应该使用什么类型的关系?

我尝试过使用 onetoone 关系,但它创建的 UNIQUE 条件是个问题。

欢迎任何想法。

干杯。

西里尔

4

2 回答 2

2

你需要一个多对多的关系。这通常使用“中间”或“链接”表来完成。在此示例中,该PlayedMatch表是链接表。

这实际上是 Player 和 Match 之间的单个多对多关系。但是,它由 2 个一对多关系表示:

玩家 [1] --> [n] PlayedMatch

比赛 [1] --> [n] PlayedMatch

Player
  Id
  Name
  Rank

Match
  Id

PlayedMatch
  Id
  MatchId
  Player1Id
  Player2Id

我看到您有一些名为 PlayerId 和 MatchId 的字符串属性。如果可以,请避免使用这些名称,因为它们通常用于外键关系。

您可能希望PlayedMatch表中有更多属性,例如WinnerId(链接到播放器)。

上面的 SQL 查询看起来像这样:

SELECT 
  *
FROM
  PlayedMatch pm
    INNER JOIN Player p1 ON pm.Player1Id = p1.Id
    INNER JOIN Player p2 ON pm.Player2Id = p2.Id
    INNER JOIN Match m ON pm.MatchId = m.Id
于 2013-03-14T22:56:25.377 回答
1

如果您想轻松找到每个玩家的所有比赛,您将需要使用ManyToMany关系。以下是类的外观的简化片段。

class Player {

    /**
     * @ORM\ManyToMany(targetEntity="Match", mappedBy="players")
     */
    protected $matches;

}

class Match {

    /**
     * @ORM\ManyToMany(targetEntity="Player", inversedBy="matches")
     */
    protected $players;

}

然后从根目录运行以下命令:

php app/console doctrine:generate:entities Your/AwesomeBundle/Entity

您将能够使用以下方法:

Match::getPlayers()
Match::addPlayer()
Player::addMatch() // probably will have an 'e' at the end of the word match
Player::getMatches() // which is the one that will give you all matches of a user

您需要在代码中限制每场比赛的玩家人数。

于 2013-03-15T05:04:48.843 回答