我有一个包含2个实现的接口SupplierInterface
:B2BSupplier
(一个Doctrine实体),RetailSupplier
(一个静态对象)。
<?php
namespace MyBundle\Model;
interface SupplierInterface {
const B2B = 'B2B';
const RETAIL = 'Retail';
/**
* @return string
*/
public function getSupplierType();
/**
* @return string
*/
public function __toString();
}
另一个实体Supply
与Supplier
有多对一的关系。通常这不成问题。但由于RetailSupplier
不是一个学说实体,我对如何继续下去感到有点沮丧。
Supply
看起来像这样:
<?php
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Blameable\Traits\BlameableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
/**
* Supply
*
* @ORM\Table(name="cir_supply")
* @ORM\Entity()
*/
class Supply
{
use BlameableEntity;
use TimestampableEntity;
/**
* @var int
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="B2BSupplier")
* @ORM\JoinColumn(name="supplier_id", referencedColumnName="id", nullable=true)
*/
protected $supplier; // <-- PROBLEM, since supplier could be B2BSupplier entity, or it could be vanilla object RetailSupplier
/**
* @ORM\ManyToOne(targetEntity="Chemical", inversedBy="supplies")
* @ORM\JoinColumn(name="chemical_id", referencedColumnName="id", nullable=false)
*/
protected $chemical;
/**
* @ORM\Column(name="external_id", type="string")
*/
protected $externalId;
//getters and setters ...
}
如果该关系可能并非始终有效,如何指定Doctrine关系?
答案 0 :(得分:2)
根据我的经验,我99%肯定你不能在当前的设置中做你想做的事。话虽如此,我可以想到一些解决方法。在我进入变通办法之前。您应该考虑是否真的想要“供应商”上的OneToOne关系,或者ManyToOne会更好地运作。 OneToOne有一些延迟加载问题,而且使用ManyToOne可以更好地解决方法3。
解决方法1:
优点:
缺点:
解决方法2:
优点:
缺点:
解决方法3 (学说继承映射):
优点:
缺点:
优点/缺点:根据所选的继承类型,您可以在数据库中使用完整的关系路径(使用foraign键),或者您可以没有任何关系。这取决于您;)在阅读继承映射的文档之后。
PS:如果我不得不选择我会选择解决方法3.它是最难实现的,但是可靠的。
希望这有助于和快乐的编码
Alexandru Cosoi