Search code examples
symfonydoctrineentity-relationshipdatabase-schema

Entity having two entities of the same type


I'm programming a small game and a database representing Players and Matches.

A player has a name, a player ID and a rank. A match has an ID, and two players.

Player

  • * id (bigint)
  • name (string)
  • playerID (string)
  • rank (integer)

Match

  • * id (bigint)
  • matchID (string)
  • playerOne (Player)
  • playerTwo (Player)

I would like to have a "matches" relationship in a Player, but how do I have an entity having two entities of same type and what type relationship should I use?

I tried a one-to-one relationship, but the UNIQUE condition it created is a problem.


Solution

  • If you want to easily find all matches per player you will need to use a ManyToMany relationship. The following is a simplified snippet of what the classes would look like.

    class Player {
    
        /**
         * @ORM\ManyToMany(targetEntity="Match", mappedBy="players")
         */
        protected $matches;
    
    }
    
    class Match {
    
        /**
         * @ORM\ManyToMany(targetEntity="Player", inversedBy="matches")
         */
        protected $players;
    
    }
    

    Then you run the following command from the root directory:

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

    And you will be able to use methods such as:

    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
    

    You will need to restrict the number of players per match in your code.