与文章或产品相关的评论实体
Comment entity related to Article or Product
我有实体 "Article" 和 "Product"。现在我想为这两个实体添加评论。我应该创建 2 个具有相同属性的不同实体 "ArticleComment" 和 "ProductComment",并与它们各自的实体建立 ManyToOne 关系,还是创建单个 "Comment" 实体并找到建立关系的方法"Article" 和 "Product" 实体。考虑到解决方案 #2,我该怎么做?
Considering solution #2, how could I do that ?
一种方法是使用 Single Table Inheritance
Single Table Inheritance is an inheritance mapping strategy where all classes of a hierarchy are mapped to a single database table. In order to distinguish which row represents which type in the hierarchy a so-called discriminator column is used.
这意味着您可以轻松创建两个单独的实体 ArticleComment
和 ProductComment
,它们都扩展 Comment
。那你就利用DiscriminatorMap
专栏提供的优势吧。
您的 Comment
实体可以持有一个名为 parent
的关系,例如,该关系将引用您的 Article
或 Product
实体。通过创建 ArticleComment
或 ProductComment
的新实例,您的鉴别器映射字段将根据您使用的类型自动填充。
这也会给您带来使用 DQL 按类型查询相关评论的优势。文档中的示例:
$query = $em->createQuery('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee');
还有更多。您可以阅读该章节 here。当然这只是一个示例,您可以使用完全不同的方法。
我有实体 "Article" 和 "Product"。现在我想为这两个实体添加评论。我应该创建 2 个具有相同属性的不同实体 "ArticleComment" 和 "ProductComment",并与它们各自的实体建立 ManyToOne 关系,还是创建单个 "Comment" 实体并找到建立关系的方法"Article" 和 "Product" 实体。考虑到解决方案 #2,我该怎么做?
Considering solution #2, how could I do that ?
一种方法是使用 Single Table Inheritance
Single Table Inheritance is an inheritance mapping strategy where all classes of a hierarchy are mapped to a single database table. In order to distinguish which row represents which type in the hierarchy a so-called discriminator column is used.
这意味着您可以轻松创建两个单独的实体 ArticleComment
和 ProductComment
,它们都扩展 Comment
。那你就利用DiscriminatorMap
专栏提供的优势吧。
您的 Comment
实体可以持有一个名为 parent
的关系,例如,该关系将引用您的 Article
或 Product
实体。通过创建 ArticleComment
或 ProductComment
的新实例,您的鉴别器映射字段将根据您使用的类型自动填充。
这也会给您带来使用 DQL 按类型查询相关评论的优势。文档中的示例:
$query = $em->createQuery('SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee');
还有更多。您可以阅读该章节 here。当然这只是一个示例,您可以使用完全不同的方法。