gpt4 book ai didi

php - Doctrine 中的多个多对一关系

转载 作者:行者123 更新时间:2023-12-04 04:40:36 24 4
gpt4 key购买 nike

一个简单的问题,但我找不到任何相关文档。

我想将一个表连接到其他两个表,在具有相同类型关系的同一列上。很简单:

我有一个地址表和一个用户表。很简单,一个用户可以有多个地址:

用户.php

/**
* @OneToMany(targetEntity="Address", mappedBy="user", cascade={"persist", "remove"})
*/
private $addresses;

地址.php
/**
* @ManyToOne(targetEntity="User", inversedBy="addresses")
*/
private $user;

现在我想添加一个新表,它也将使用地址(一个供应商也可能有很多地址)。

供应商.php
/**
* @OneToMany(targetEntity="Address", mappedBy="**???**", cascade={"persist", "remove"})
*/
private $addresses;

显然我不能按用户映射,因为它从地址指向用户。我想我可以在地址表中添加另一个外键,但我想知道是否有更好的方法来做到这一点,并继续为用户和地址使用相同的外键列。

最佳答案

您只需要指定一个 mappedBy当存在双向关系时,属性来确定哪一方是拥有方。

从文档:

http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#owning-side-and-inverse-side

  • A bidirectional relationship has both an owning side and an inverse side.
  • A unidirectional relationship only has an owning side.
  • The owning side of a relationship determines the updates to the relationship in the database.

...

The following rules apply to bidirectional associations:

The inverse side of a bidirectional relationship must refer to its owning side by use of the mappedBy attribute of the OneToOne, OneToMany, or ManyToMany mapping declaration. The mappedBy attribute designates the field in the entity that is the owner of the relationship.



在您的情况下,您只有单向关系,这意味着您不必指定 mappedBy ,您也许可以将其排除在外。

或者您可以将供应商添加到 Address 类:
/**
* @ManyToOne(targetEntity="Supplier", inversedBy="addresses")
*/
private $supplier;

然后允许您设置 mappedBy="supplier"Supplier.php
/**
* @OneToMany(targetEntity="Address", mappedBy="supplier", cascade={"persist", "remove"})
*/
private $addresses;

关于php - Doctrine 中的多个多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18961412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com