【问题标题】:Doctrine2 Mapping: 2 fields mapped to one field (ManyToOne)Doctrine2 Mapping:2 个字段映射到一个字段(ManyToOne)
【发布时间】:2012-11-27 02:17:36
【问题描述】:

我有 2 个实体,即 Match 和 Team。一个团队可以有一对多的比赛。但是,我的 Match 实体 consts 的 2 个字段引用了相同的实体 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;

【问题讨论】:

  • 我也有同样的问题,但是你需要加入 OR 条件:homeTeam OR AwayTeam,就像我的情况一样,我需要加入 AND 条件。

标签: php orm doctrine-orm


【解决方案1】:

探索Doctrine's official docs后:不能添加多个mappedBy列。取而代之的是,您可以选择:

  1. Match 创建一个自定义存储库并定义方法getAllMatchesForTeam($team)
  2. Team上定义适当的关系$homeMatches$awayMatches +方法getAllMatches()$homeMatches$awayMatches的联合结果在那里

在这里阅读更多:

  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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2020-12-20
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多