首先,我想提前为问题标题道歉,因为它可能无法理想地解释我正在处理的情况。我做了一些研究,但没能找到合适的解决方案。
我的案例:
我有一个实体,比如说一个事件,它代表我网站上的客户执行的事件。它可以是不同的类型,例如:page_view、comment、login、purchase 等。我想做的是为每个事件分配补充数据,例如。对于评论事件,补充数据将是评论实体,对于购买一系列产品实体等。 现在,我只是将事件类型定义为 ActivityInterface 中的常量,然后使用该值获取一个 EntityManager 实例,该实例能够根据 http 请求中提供的参数解析正确的实体。这个解决方案有很多缺点,我不确定这是否是正确的方法。
你们能帮我解决问题,给我一些提示或将我重定向到一些关于如何捕获这个主题的有用出版物吗?谢谢。
最佳答案
我建议使用 Mapped Superclass像这样:
/** @MappedSuperclass */
class Activity
{
/** @Id @Column(type="integer") */
protected $id;
/** @Column(type="string") */
protected $generalActivityProperty;
// ... more fields and methods
}
/** @Entity */
class Comment extends Activity
{
/** @ManyToOne(targetEntity='CommentEntity') */
private $commentEntity;
// ... more fields and methods
}
/** @Entity */
class Purchase extends Activity
{
/** @OneToMany(targetEntity='ProductAssociations') */
private $products;
// ... more fields and methods
}
这将为每个类创建一个表(但不为“事件”创建),每个表包含“事件”中定义的所有字段/方法以及特定类中定义的其他字段/方法。
您甚至可以通过 entityManager->getRepository('Acticity')->find()
查询所有事件,例如并获取 Comment、PageView 等对象的列表。
它没有经过测试,但您应该知道如何去做。
您也可以使用Single Table Inheritance
或Class Table Inheritance
。看看here .
但我想在您的情况下,映射父类(super class)应该是完美的。
关于php - Doctrine2 架构设计 - 带有补充数据的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42791819/