超级多态事件架构

时间:2016-07-18 20:56:36

标签: sql postgresql

我希望能够跟踪用户在我的网站上执行的每项操作。

动作可以来自visitoruser(两者都是人类)。

操作可能会影响主题(visitoruser

操作可以有object,可以是任何其他数据库表

一些例子:

User A (actor)User B (subject)分配给conversation (object)

User A (actor)创建team (object)

User B (actor)已将Visitor (subject)移至group C (object)

在我的应用程序中,我想要一个所有事件的提要,并且对于每个事件,准确显示它引用的actor,subject(如果有的话)和对象

我在想像

create table actors ( -- contains as many rows as there are people
   int ID,
)

create table roles ( -- roles like for both human and object roles such as: Visitor, Team, User, Conversation, Group
   int ID,
   nvarchar(max) Name
)

create table actors_roles ( -- associates people with roles
   int Actor_ID, -- FK to actors.ID
   int Role_ID -- FK to roles.ID
)

create table objects ( -- associates objects with roles
   int ID,
)

create table object_roles ( -- associates objects with roles
   int Object_ID, -- FK to object.ID
   int Role_ID -- FK to roles.ID
)

create table tEvent (
   int ID,
   int Type_ID,
   int Actor_ID, -- FK to actors.ID
   int Subject_ID -- FK to actors.ID
   int Object_ID -- FK to objects.ID
)

除了这些表之外,roles中的每个记录都有一个相应的独立表,用外键保存与该对象相关的所有数据。

我希望得到一些关于这种结构的反馈,如果它是可扩展的,或者可能有更好的方法来实现这个目标?

感谢Daniel A. Thompson推动我朝这个方向发展

1 个答案:

答案 0 :(得分:1)

根据您的要求,我建议采用以下方案:

-- roles for both human and object roles such as:
-- Visitor, Team, User, Conversation, Group
CREATE TABLE tRole ( 
   int ID,
   nvarchar(max) Name
)

-- contains as many rows as there are people
CREATE TABLE tActor ( 
   int ID,
   int Role_ID -- FK to tRole.ID
)

-- contains as many rows as there are objects 
CREATE TABLE tObject ( 
   int ID,
   int Role_ID -- FK to tRole.ID
)

CREATE TABLE tEvent (
   int ID,
   int Type_ID,
   int Actor_ID, -- FK to tActor.ID
   int Subject_ID -- FK to tActor.ID
   int Object_ID -- FK to tObject.ID
)