【问题标题】:Doctrine: owning side and inverse side学说:拥有的一面和相反的一面
【发布时间】:2020-01-27 06:08:24
【问题描述】:

您好,在 de Doctrine 文档中说: 'Doctrine 只会检查关联的拥有方是否有更改。'

我在这里阅读了其他帖子,但我找不到一个例子让我理解为什么如果反面发生变化,这不会被教义坚持。

我以帖子为例:Understanding of “owning side” and “inverse side” concepts in Doctrine

Customer实体:

class Customer
{
    // ...

    /** ONE-TO-ONE BIDIRECTIONAL, OWNING SIDE
     * @ORM\OneToOne(targetEntity="Company", inversedBy="customer")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
     */
    private $company;

    // ...

    /**
     * Set company method
     *
     * @param Company $company
     */
    public function setCompany( Company $company )
    {
       $this->company = $company; 
       $company->setCustomer( $this );
    }
}

Company实体:

class Company
{
    // ...

    /** ONE-TO-ONE BIDIRECTIONAL, INVERSE SIDE
     * @OneToOne(targetEntity="Customer", mappedBy="company")
     */
    private $customer;

    // ...
}

我有两个问题: 1. 如何在公司实体中设置客户方法? (以反映此数据库模型) 2. 在这种情况下,公司实体的变更可能无法通过原则来坚持?

【问题讨论】:

标签: php doctrine associations object-model


【解决方案1】:

把你脑海中关于Owning sideInversed side的所有东西都拿出来。 这些只是帮助 Doctrine 将数据水合到相关模型中的一些概念

阅读 Doctrine 文档中的以下引文。这可能有助于理解Owning sideInversed side 的概念。

“拥有方”和“反方”是 ORM 的技术概念 技术,而不是您的领域模型的概念。你认为什么 域模型中的拥有方可能与 拥有方是为教义。这些是无关的。

Doctrine doc 中的另一个引文:

Doctrine 只会检查关联的拥有方 变化。

这意味着关联的拥有方是具有包含外键的表的实体。因此,包含外键的表只会被原则考虑更改。

再次来自 Doctrine 文档:

  • OneToOne - 当前实体的一个实例指代被引用实体的一个实例
  • OneToOne 关联的拥有方是具有包含外键的表的实体

这里 Company 的一个实例是指被引用实体 Customer 的一个实例,反之亦然。

当我们像上面的示例一样谈论 OneToOne 关联时,拥有方将是具有包含外键的表的实体,因此,Customer 实体。

通过您的示例,Doctrine 将创建如下表:

CREATE TABLE Company (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;

CREATE TABLE Customer (
    id INT AUTO_INCREMENT NOT NULL,
    company_id INT DEFAULT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;
ALTER TABLE Customer ADD FOREIGN KEY (company_id) REFERENCES Company(id);

现在,如果您想获取与公司关联的客户的数据,那么查询将是:

SELECT Company.id AS CompanyID, Customer.id AS CustomerID
FROM Company
LEFT JOIN Customer ON Company.id = Customer.company.id;

此类查询的返回结果将由 Doctrine 合并到两个模型中。

【讨论】:

  • 谢谢,我仍然有疑问,我需要一个 Doctrine 会忽略坚持的例子。例如:$company = new Company(); $entityManager->persist($company); $entityManager->flush();这不会保存在数据库中?
  • 是的,这也将保存在数据库中。你注意到Customer 实体中的setCompany() 方法了吗?这是由原则通过使用/检查关联的拥有方来实现的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2013-03-14
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多