Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 Mapping: 2 fields mapped to one field (ManyToOne)

I have 2 entities, namely Match and Team. A Team can have one to many Matches. However, my Match entity consts of 2 fields which reference the same entity, Team. They are $homeTeam and $awayTeam. How do I reference the same field in Team, $matches, as a Bidirectional relationship?

My current non-working code is below:

My Match Entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="match")
 **/
class Match {

    /**
     * @ORM\ManyToOne(targetEntity="Team", inversedBy="matches")
     * @ORM\JoinColumn(name="home_team_id", referencedColumnName="id")
     * **/
    protected $homeTeam;

    /**
     * @ORM\ManyToOne(targetEntity="Team", inversedBy="matches")
     * @ORM\JoinColumn(name="away_team_id", referencedColumnName="id")
     * **/
    protected $awayTeam;

My Team Entity (incorrect I would presume?):

/**
 * @ORM\Entity
 * @ORM\Table(name="team")
 * **/
class Team {

    /** @ORM\OneToMany(targetEntity="Match", mappedBy="homeTeam", mappedBy="awayTeam") **/
    protected $matches;
like image 489
Blyde Avatar asked Nov 27 '12 02:11

Blyde


1 Answers

After exploring Doctrine's official docs: you can't add multiple mappedBy columns. Instead of this, you can choose between:

  1. Create a custom repository for Match and define method getAllMatchesForTeam($team)
  2. Define appropriate relations $homeMatches and $awayMatches + method getAllMatches() on Team and union results of $homeMatches and $awayMatches there

Read more here:

  1. https://stackoverflow.com/questions/13922047/symfony2-doctrine2-how-to-implement-methods-on-entity-to-retrieve-related-ent
  2. Custom repository class in Symfony2
  3. Fetching data through a custom repository in a Twig extension
  4. How can I access a service outside of a controller with Symfony2?
like image 108
Dmitriy Avatar answered Sep 18 '22 12:09

Dmitriy