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

I have 2 objects, namely Match and Team. A team can have one, many matches. However, my Match entity consts consists of 2 fields that reference the same Team object. These are $ homeTeam and $ awayTeam. How do I refer to the same field in teams, $ match, as a bi-directional relationship?

My current broken 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 (am I guessing wrong?):

 /** * @ORM\Entity * @ORM\Table(name="team") * **/ class Team { /** @ORM\OneToMany(targetEntity="Match", mappedBy="homeTeam", mappedBy="awayTeam") **/ protected $matches; 
+7
source share
1 answer

After examining Doctrine's official docs : you cannot add multiple mappedBy columns. Instead, you can choose between:

  • Create a custom repository for Match and define the getAllMatchesForTeam($team) method
  • Define the appropriate relationship $homeMatches and $awayMatches + method getAllMatches() on Team and the results of combining $homeMatches and $awayMatches there

More details here:

+7
source

All Articles