Doctrine2映射:映射到一个字段的2个字段(ManyToOne) [英] Doctrine2 Mapping: 2 fields mapped to one field (ManyToOne)
本文介绍了Doctrine2映射:映射到一个字段的2个字段(ManyToOne)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前的非工作代码如下:
我的匹配实体:
/ **
* @ 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)** /
保护$ match;
解决方案
探索 Doctrine的官方文档:您不能添加多个 mappedBy
列。而不是这样,您可以选择:
- 为
匹配
创建自定义存储库并定义方法getAllMatchesForTeam($ team)
- 定义适当的关系
$ homeMatches
和$ awayMatches
+方法getAllMatches()
在团队
和$ homeMatches
和$ awayMatches
有
在此阅读更多:
- https://stackoverflow.com/questions/13922047/symfony2-doctrine2-how-to-implement-methods- on-entity-to-retrieve-related-ent
- 自定义存储库类Symfony2
- Fetchin g数据通过Twig扩展名中的自定义存储库
- 如何使用Symfony2访问控制器之外的服务?
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;
解决方案
After exploring Doctrine's official docs: you can't add multiple mappedBy
columns. Instead of this, you can choose between:
- Create a custom repository for
Match
and define methodgetAllMatchesForTeam($team)
- Define appropriate relations
$homeMatches
and$awayMatches
+ methodgetAllMatches()
onTeam
and union results of$homeMatches
and$awayMatches
there
Read more here:
- 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?
这篇关于Doctrine2映射:映射到一个字段的2个字段(ManyToOne)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文