Doctrine2 Mapping: 2 fields mapped to one field (M

2019-03-26 08:37发布

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;

1条回答
\"骚年 ilove
2楼-- · 2019-03-26 09:09

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?
查看更多
登录 后发表回答