如何在 MS Access 中创建(类型,ID)(又名“多态”)外键列?

发布于 2024-07-06 02:18:51 字数 712 浏览 5 评论 0原文

在 Ruby-on-Rails 中,这称为“多态关联”。

我的应用程序中有几个 Commentable 内容,每个内容的表格如下:

Post
id | title | text | author (FK:Person.id) | ...

Person
id | name | ...

Photo
id | title | owner (FK:Person.id) | path | ...

我想添加一个 Comments 表,如下所示:

Comments
id | commentable_type | commentable_id | text | author (FK:Person.id)

我知道我丢失了数据库的引用这种方式完整性,但唯一的其他选择是拥有多个 Comments 表:PostCommentsPersonCommentsPhotoComments、 ...

现在的问题是:

我如何构建一个表单来了解如何进行查找,首先从 Comments.commentable_type 获取表名,然后来自 Comments.commentable_id 的 id?

In Ruby-on-Rails, this is called a "polymorphic association."

I have several Commentable things in my application, the tables for each are below:

Post
id | title | text | author (FK:Person.id) | ...

Person
id | name | ...

Photo
id | title | owner (FK:Person.id) | path | ...

I'd like to add a Comments table as follows:

Comments
id | commentable_type | commentable_id | text | author (FK:Person.id)

I understand that I lose the database's referential integrity this way, but the only other option is to have multiple Comments tables: PostComments, PersonComments, PhotoComments, ...

And now for the question:

How can I build a form that will grok how to do the lookup, first by getting the table name from Comments.commentable_type and then the id from Comments.commentable_id?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南…巷孤猫 2024-07-13 02:18:53

我相信很多人都为这类事情制作元表。 和你描述的差不多。

I believe many people make meta-tables for that sort of thing. Pretty much exactly as you described it.

半仙 2024-07-13 02:18:51

这种技术在 SQL 世界中通俗地称为“子类化”。 有关有效示例(SQL Server 语法,但很容易适应 MS Access),请参阅 David Porta 的博客。

在您的场景中,所有评论共有的数据项将位于您的评论表中; 每种类型特定的任何内容都将在专门的表中,例如 PhotoComments 等。请注意,FK 应该是 ID 加上类型的两列组合,这经常被忽视,但对于引用完整性至关重要,例如您不这样做希望键入的内容作为照片评论出现在 PersonComments 表中。

This technique is known colloquially in the SQL world as 'subclassing'. For a worked example (SQL Server syntax but is easily adapted for MS Access), see David Porta's blog..

In your scenario, the data items common to all comments would be in your Comments table; anything specific to each type would be in specialized tables such as PhotoComments, etc. Note the FK should be the two-column compound of the ID plus the type, something which is often overlooked but is essential to referential integrity here e.g. you don’t want something typed as a photo comment appearing in the PersonComments table.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文