8

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;
Blyde
  • 2,923
  • 2
  • 18
  • 16
  • I have the same problem, but you need to join with OR condition: homeTeam OR AwayTeam, as in my case i need to join with AND condition. – Dmytro Dec 16 '12 at 12:53

1 Answers1

9

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?
Community
  • 1
  • 1
Dmytro
  • 5,443
  • 2
  • 52
  • 50