【问题标题】:Is there a way to Implement Polymorphic Relation with Doctrine 2 in Symfony 4有没有办法在 Symfony 4 中用 Doctrine 2 实现多态关系
【发布时间】:2019-06-18 22:02:30
【问题描述】:

在基本层面,我想要一个 invoice 实体,它可以有和 InvoiceTo 字段。 InvoiceTo 字段应该与IndividualCustomer 实体或CompanyCustomer 实体具有ManyToOne 关系。

到目前为止的所有阅读都使我相信这是 Doctrine Inheritance Mapping 的一个案例,但这只是我无法理解文档或迄今为止我发现的极少数讨论的博客学说中的多态关系。

我想实现如下(如果可能的话),

// First Example, were the invoice is sent to an IndividualCustomer
$individualCustomer = $this->getDoctrine()
        ->getRepository(individualCustomer::class)
        ->find($id);

$invoiceTo = new InvoiceTo($individualCustomer);

$invoice = new Invoice();
$invoice->setAmt(100.00);
$invoice->setInvoiceTo($invoiceTo);


// Second Example, were the invoice is sent to CompanyCustomer
$companyCustomer = $this->getDoctrine()
        ->getRepository(companyCustomer::class)
        ->find($id);

$invoiceTo = new InvoiceTo($companyCustomer);

$invoice = new Invoice();
$invoice->setAmt(100.00);
$invoice->setInvoiceTo($invoiceTo);

我真的很感激任何相同的指针。出于某种原因,所有文档似乎都非常神秘。感谢您的时间和帮助。

【问题讨论】:

  • 为什么不在 InvoiceTo 中创建两个多对一属性,并让构造函数(和/或 getter/setter)有点智能,以便它检查类并将值分配给正确的属性(和/或查看设置了哪个属性)?如果您想要“更简单”的关联,继承映射不​​是一个很好的选择。但是,很少的代码可以走很远
  • @Jakumi 感谢指针,它对于这样一个更简单的关联确实有意义。关于查询将如何工作或受到此类实施影响的任何粗略想法。我想采用Inheritance mapping 的方式,因为其中很多都会被教义妥善处理(我猜)。
  • 说实话,我尝试过两次像...一样使用继承映射。两次我最终都浪费了太多时间试图让教义做我想做的事,而且两次额外的领域和一些非常简单的逻辑最终都变得更容易了。实际上我最近看到了一些关于继承映射的问题,并且可能还有教程。不过,我不能给出更好/具体的指示,抱歉;o/
  • 我会说这是可能的,但就目前而言,你的问题太笼统了。有没有什么具体的东西你不能从文档中弄出来?您能否大致介绍一下您的实体?

标签: php database symfony doctrine-orm polymorphic-associations


【解决方案1】:

为了使您的字段invoiceTo 引用IndividualCustomerCompanyCustomer,一个解决方案是创建一个父类;假设CustomerIndividualCustomerCompanyCustomer 继承自其中。 从那里,您的invoiceTo 字段可以直接定位Customer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2023-04-10
    • 1970-01-01
    • 2018-07-12
    • 2013-12-04
    • 1970-01-01
    • 2013-03-12
    相关资源
    最近更新 更多