实体具有两个相同类型的实体

时间:2013-03-14 22:50:47

标签: symfony doctrine entity-relationship database-schema

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

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

播放器

  • id(bigint)
  • name(string)
  • playerID(string)
  • 排名(整数)

匹配

  • id(bigint)
  • matchID(string)
  • playerOne(玩家)
  • playerTwo(玩家)

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

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

欢迎任何想法。

干杯。

西里尔

2 个答案:

答案 0 :(得分:2)

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

这实际上是播放器和匹配之间的单个多对多关系。然而,它由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

答案 1 :(得分: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

您需要在代码中限制每场比赛的球员数量。

相关问题