与自身的多对多关系

Many to many relationship with itself

我的数据库关系需要一些帮助。我的问题是我不知道我是否以正确的方式解决了这个问题。我有一个应用程序,用户可以在其中与其他用户交朋友,类似于在 Facebook 上建立友谊。

╔═══════════╗
║   Users   ║
╠═══════════╣
║ #id       ║ 
║ *username ║
║ *password ║
╚═══════════╝

╔══════════════╗
║ User_friends ║
╠══════════════╣
║ *user_id     ║
║ *friend_id   ║
╚══════════════╝    

╔════════════════╗
║ Friend_request ║
╠════════════════╣
║ #id            ║
║ *user_id       ║
║ *friend_id     ║
║ *created_at    ║
║ *updated_at    ║
╚════════════════╝

用户 John Doe 想登录我的应用程序并向 Jane Doe 发送好友请求,因此记录将存储在 Friend_request 并且当 Jane Doe 登录到应用程序时,她会看到一条通知,表明有人想要建立友谊。当 Jane Doe 接受 John Doe 的 友谊请求时 我想将两条记录存储到 User_friends 因为 John DoeJane Doe 的朋友并且 Jane DoeJohn Doe 有友谊

我不确定我是否以正确的方式解决了这个问题。

你所做的事情是合理和直接的。

PS 与您指定(通过#)的 PRIMARY KEY 相比,还有更多候选键(UNIQUE NOT NULL 列集不包含较小的列集):

Users (username) -- likely -- though not on Stack Overflow
User_friends (user_id, friend_id)
Friend_request (user_id, friend_Id)

PPS Re title "Many to many relationship with itself": 我猜你的意思是在 User_friendsFriend_request 实体中 class 用户有一个 "many to many relationship with itself".表表示(应用程序)关系。因此,行中的值是相关的,它们指定的实体也因此是相关的。从 user_idfriend_id 列到 Users id 有外键。这些通常 称为 "relationships" 尽管它们是 facts/constraints。 (如果您查询用户的用户名并请求或接受朋友,那么您将 JOIN Users 与自己。)