简体   繁体   English

原则通过字段值覆盖关系

[英]Doctrine override relation by field value

Take a look at the following model: 看一下以下模型:

class Team

    /**
     * @id
     * @ManyToOne(targetEntity="Person")
     * @JoinColumn(name="id_manager", referencedColumnName="id")
     */
    protected $manager;

    /** 
     * @id
     * @ManyToOne(targetEntity="Stadium")
     * @JoinColumn(name="stadium", referencedColumnName="stadium")
     */
    protected $stadium;

When I query for a team using array hidration I do: 当我使用数组隐藏查询团队时,我会执行以下操作:

$qb->select(['a', 'b', 'c']);
$qb->from(Team::class, 'a');
$qb->leftJoin('a.manager', 'b');
$qb->leftJoin('a.stadium', 'c');

$teams = $qb->getQuery()->getArrayResult();

For each team the structure is this: 对于每个团队,结构如下:

[
    "id_manager": 3,
    "manager": [
        "id": 3,
        "name": "Billy"
    ],
    "stadium": 8
]

See how "manager" is loaded as an array (as expected), but "stadium". 查看如何将“管理器”加载为数组(按预期方式),但如何加载“体育场”。 At the first sign looks like if the relation field has the same name as the column it keep the column value. 在第一个符号看起来像,如果关系字段具有与列相同的名称,它将保留列的值。 Is there a way to avoid this situation without renaming the field $stadium neither column? 有没有一种方法可以避免这种情况,而不必重命名字段$stadium both?

PS: $qb->select(['a', 'b', 'c as stadium2']); PS: $qb->select(['a', 'b', 'c as stadium2']); did not work. 不工作。

EDIT I have noticed that if I delete the @id annotation I get the structure expected. 编辑我已经注意到,如果删除@id批注,则会得到预期的结构。

So manager's id should be the primary key for team as well? 那么经理的ID也应该是团队的主键吗? So your primary key is a foreign key at the same time? 那么您的主键同时是外键吗? Don't recommend that. 不建议那样。

I propose a team's primary key which is independent and have a relationship to the manager in a second attribute. 我提出了一个团队的主键,该主键是独立的,并且在第二个属性中与经理有关系。

If you need the manager's id in your result you could achieve that eg in your custom respository or by an additional attribute and its getter in your Team class which is not mapped to ORM. 如果在结果中需要经理的ID,则可以在自定义存储库中实现,也可以通过Team类中未映射到ORM的其他属性及其获取方法来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM