2

我有许多不相关的实体,我希望能够将 FileAttachment 实体添加到其中。我正在使用 Doctrine2(在 Symfony 项目的上下文中)。

在我开始使用 Doctrine 之前,我会制作一个带有鉴别器列的连接表,如下所示:

file_id
entity_id
entity_type

据我所知,对于 Doctrine,我需要为每个具有 FileAttachment 关联的实体类型提供一个联结表。如果可能的话,我宁愿避免这种情况。我在这里找到了 NHibernate 解决方案。是否有可能用 Doctrine 做类似的事情,有人可以指点我一些文档吗?我已经阅读(现在很多次了!)Doctrine 手册的第6章和第7章。但我没有找到我要找的东西。

4

1 回答 1

2

尝试创建一个抽象FileAttachment类并为每个entity_typeie EntityOneAttachmentEntityTwoAttachment等扩展它。

扩展类都将引用相同的连接列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;  
}

然后将每个实体映射到其各自的附件类。

class EntityOne
{
  /**
   * @ORM\OneToMany(targetEntity="EntityOneAttachment", mappedBy="entityOne")
  **/        
  protected $fileAttachments;
}
于 2014-06-10T08:10:17.280 回答