dag*_*goo 4 javascript postgresql database-design node.js prisma
我有一个用户模型,我想添加关注/关注者系统,为此我认为我需要创建一个单独的表,如下所示
id | user_id | follower_id
1 | 20 | 45
2 | 20 | 53
3 | 32 | 20
Run Code Online (Sandbox Code Playgroud)
但我不知道如何为此创建架构,我所做的是:
model User {
id Int @id @default(autoincrement())
username String
Follows Follows[]
}
model Follows {
id Int @id @default(autoincrement())
following_id Int?
follower_id Int?
user_Following User @relation(fields: [following_id], references: [id])
user_Follower User @relation(fields: [follower_id], references: [id])
}
Run Code Online (Sandbox Code Playgroud)
但这当然行不通并且给了我一个错误
Tas*_*mam 10
这是我建议对模式进行建模的方法。
model User {
id String @id @default(autoincrement())
username String
followers Follows[] @relation("following")
following Follows[] @relation("follower")
}
model Follows {
follower User @relation("follower", fields: [followerId], references: [id])
followerId String
following User @relation("following", fields: [followingId], references: [id])
followingId String
@@id([followerId, followingId])
}
Run Code Online (Sandbox Code Playgroud)
变化
followerId并被followingId强制执行。Follows当其中任何一个都不存在时,拥有关系表就没有意义。(如果没有一名用户关注和一名要关注的用户,您就无法建立关注关系)。@@id([followerId, followingId])代表表中的主键Follows。单独的id字段是多余的。4 当然是可选的,但我建议仍然遵循它。
您可以在 Prisma 文档中自我反应文章的多对多小节中找到有关此内容的更多详细信息。
| 归档时间: |
|
| 查看次数: |
2854 次 |
| 最近记录: |