我有许多不相关的实体,我希望能够将 FileAttachment 实体添加到其中。我正在使用 Doctrine2(在 Symfony 项目的上下文中)。
在开始使用 Doctrine 之前,我会创建一个带有鉴别器列的连接表,如下所示:
file_id
entity_id
entity_type
据我所知,对于 Doctrine,我需要为每个具有 FileAttachment 关联的实体类型提供一个联结表。如果可能的话我宁愿避免这种情况。我找到了一个 NHibernate 解决方案 here 。是否可以用 Doctrine 做类似的事情,有人可以给我指出一些文档吗?我已经读过(现在已经很多次了!)章节6和 7 Doctrine 手册。但我没有找到我要找的东西。
最佳答案
尝试创建一个抽象FileAttachment
类并为每个entity_type
扩展它,即EntityOneAttachment
、EntityTwoAttachment
等。
扩展类都将引用相同的连接列entity_id
,但将其映射到各自的实体。
/**
* @ORM\Entity
* @ORM\Table(name="file_attachment")
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="entity_type", type="string")
* @ORM\DiscriminatorMap({"entity_one_attachment" = "EntityOneAttachment", "entity_two" = "EntityTwoAttachment"})
*/
abstract class FileAttachment
{
/**
* @ORM\ManyToOne(targetEntity="File")
* @ORM\JoinColumn(name="file_id", referencedColumnName="id", nullable=false)
**/
protected $file;
}
/**
* @ORM\Entity
*/
class EntityOneAttachment extends FileAttachment
{
/**
* @ORM\ManyToOne(targetEntity="EntityOne", inversedBy="fileAttachments")
* @ORM\JoinColumn(name="entity_id", referencedColumnName="id", nullable=false)
**/
protected $entityOne;
}
/**
* @ORM\Entity
*/
class EntityTwoAttachment extends FileAttachment
{
/**
* @ORM\ManyToOne(targetEntity="EntityTwo", inversedBy="fileAttachments")
* @ORM\JoinColumn(name="entity_id", referencedColumnName="id", nullable=false)
**/
protected $entityTwo;
}
然后将每个实体映射到其各自的 Attachment 类。
class EntityOne
{
/**
* @ORM\OneToMany(targetEntity="EntityOneAttachment", mappedBy="entityOne")
**/
protected $fileAttachments;
}
关于doctrine - 与 Dotrine 的连接表中的鉴别器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23997550/