简体   繁体   中英

Foreign keys in database for php blog

Right now I'm working on a small blog project and I have 2 tables in my database: users and posts. I want to display name of the author of the post so I thought I should make foreign key for user in post table. But what if I would create normal column called for example user_id and just save there id of the author. Then while I would like to display post i could join both tables and display content of post and name of the author.

Does creating foreign key have some adventages?

Either way, you are going to need a "normal" column, such as user_id .

The advantage of making the user_id a foreign key is that then, the database will enforce referential integrity. This means it won't allow you to set on a post a user that does not exist, nor will it allow you to delete a user who has one or more posts (without also deleting the relevant posts).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM