我有2个实体,即Match和Team.一个团队可以拥有一对多的比赛.但是,我的Match实体包含两个引用同一实体Team的字段.他们是$homeTeam和$awayTeam.如何将Team,$matches中的相同字段作为双向关系引用?
我目前的非工作代码如下:
我的匹配实体:
/** * @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;
我的团队实体(我猜不正确?):
/** * @ORM\Entity * @ORM\Table(name="team") * **/ class Team { /** @ORM\OneToMany(targetEntity="Match",mappedBy="homeTeam",mappedBy="awayTeam") **/ protected $matches;
在探索
Doctrine’s official docs之后:您无法添加多个mappedBy列.除此之外,您可以选择:
>为Match创建自定义存储库并定义方法getAllMatchesForTeam($team)
>在$homeMatches和$awayMatches的Team和union结果上定义适当的关系$homeMatches和$awayMatches方法getAllMatches()
在这里阅读更多:
> https://stackoverflow.com/questions/13922047/symfony2-doctrine2-how-to-implement-methods-on-entity-to-retrieve-related-ent
> Custom repository class in Symfony2
> Fetching data through a custom repository in a Twig extension
> How can I access a service outside of a controller with Symfony2?