doctrine - 与 Dotrine 的连接表中的鉴别器

标签 doctrine junction-table discriminator

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

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

file_id
entity_id
entity_type

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

最佳答案

尝试创建一个抽象FileAttachment类并为每个entity_type扩展它,即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;  
}

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

class EntityOne
{
  /**
   * @ORM\OneToMany(targetEntity="EntityOneAttachment", mappedBy="entityOne")
  **/        
  protected $fileAttachments;
}

关于doctrine - 与 Dotrine 的连接表中的鉴别器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23997550/

相关文章:

grails - 初始化使用Grails鉴别器配置的子类对象

php - Doctrine 未在 Doctrine :schema:update 上创建一对多关系

mysql - 我在查询生成器 SYMFONY 中遇到问题

php - Symfony2 - Doctrine 和 FOSUserBundle - 错误的注释

asp.net - Entity Framework 中与联结表的多对多关系?

sql - 联结表的主键/聚集键

sequelize.js - Sequelize 多对多 M :N relationship not functioning. 错误: 'SequelizeEagerLoadingError:${model1} is not associated to ${model2}'

inheritance - Grails继承映射中的鉴别器问题

mysql - Symfony Doctrine 迁移重命名表与关系

c# - 如何使鉴别器表更有用