在一张表中定义多个外键到多个表
我有3个模型:
帖子:
- id
- 标题
- 正文
照片:
- id
- 文件路径
评论:
- id
- post_id
- 正文
和数据库中的相应表。现在,如果我只想为我的帖子添加评论,我可以简单地添加以下外键:ALTER TABLE comment ADD FOREIGN KEY (post_id) REFERENCES post (id)
。但我想对其他模特(照片、个人资料、视频等)发表评论,并将所有评论保留在一个表中。在这种情况下我该如何定义外键(我肯定需要 ORM 的外键)?
I have 3 models:
Post:
- id
- title
- body
Photo:
- id
- filepath
Comment:
- id
- post_id
- body
and corresponding tables in DB. Now, if I want to have comments only for my posts I can simply add following foreign key: ALTER TABLE comment ADD FOREIGN KEY (post_id) REFERENCES post (id)
. But I want to have comments for other models (photo, profile, video, etc) and keep all comments in one table. How can I define foreign keys (i definitely need FKs for ORM) in such case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以这样做:
仍然有可能拥有属于两个不同项目的评论。如果您认为这是一个问题,我可以尝试改进设计。
You could do this:
There's still the possibility of having a comment that belongs to two different items. If you think that would be an issue I can try to improve the design.
找到一些常见的内容来发布、配置文件等——由于缺乏更好的词,我使用了实体,然后是子类型。
Find something common to post, profile, etc -- I have used
Entity
for a lack of better word, then subtype.如果您想知道单个列是否可以有多个外键,那么答案是否定的,您不能。
如果需要,您可以拥有单独的外键。因此,您可以像这样修改评论表 -
并且,您必须确保评论表中的 PostID、PhotoID 和 ProfileID 列允许为空,并且还可能将默认值设置为空。
这是实现此目的的 DDL -
If you want to know if you can have multiple foreign keys to a single column then the answer is no you cant.
You can have separate foreign keys if you want to. So your can modify your comment table like this -
And, you will have to ensure that you allow nulls in PostID,PhotoID and ProfileID columns in Comment table and also perhaps set the default value to null.
Here is the DDL to achieve this -
在这种情况下,您可以添加一个包含“照片”、“个人资料”的 ENUM 字段...它将是外键的第二部分
In that case you can add an ENUM field which will contain 'photo','profile'... It will be the second part of the foreign key
由于照片评论与帖子评论不同,我会将它们存储在单独的相关表中。所以我会有:
Post:
PostComment:
Photo:
PhotoComment:
使用 id 作为 PK 的名称是一种不好的做法,它使报告变得更加困难,而且更有可能在复杂查询中无意中连接到错误的表。如果您使用 tablenameID 并始终对 Fks 使用相同的名称,那么也更容易查看关系。
Since photo comments are not the same things as post comments, I would store them in separate related tables. So I would have have:
Post:
PostComment:
Photo:
PhotoComment:
It is a poor practice to use id as the name of your PK, it makes it much harder to do reporting and much more likely to inadvertently join to the wrong table in a complex query. If you use tablenameID and consistently use the same name for Fks then it is easier to see the relationships as well.