Prisma following/follower 关系模式
Prisma following/follower relationship schema
我有一个用户模型,我想添加 following/followers 系统,为此我想我需要创建一个单独的 table,如下所示
id | user_id | follower_id
1 | 20 | 45
2 | 20 | 53
3 | 32 | 20
但我不知道如何为此创建架构,我所做的是:
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])
}
但这当然行不通并且给我一个错误
这是我建议的模式建模方式。
model User {
id String @id @default(autoincrement())
username String
followers Follows[] @relation("follower")
following Follows[] @relation("following")
}
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])
}
变化
- 用户 table 有两个关系字段而不是一个。
followerId
和 followingId
是强制性的。当其中任何一个不存在时,拥有 Follows
关系 table 并没有真正意义。 (没有一个用户关注和一个用户关注,你不能有关注关系)。
@@id([followerId, followingId])
表示Follows
table中的主键。单独的 id
字段是多余的。
- 将字段名称更改为驼峰式命名,这是 Prisma 中推荐的约定。
4 是可选的当然,但我建议遵循它 none 少。
您可以在 Prisma 文档的 self-reation article 的多对多小节中找到更多详细信息。
我有一个用户模型,我想添加 following/followers 系统,为此我想我需要创建一个单独的 table,如下所示
id | user_id | follower_id
1 | 20 | 45
2 | 20 | 53
3 | 32 | 20
但我不知道如何为此创建架构,我所做的是:
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])
}
但这当然行不通并且给我一个错误
这是我建议的模式建模方式。
model User {
id String @id @default(autoincrement())
username String
followers Follows[] @relation("follower")
following Follows[] @relation("following")
}
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])
}
变化
- 用户 table 有两个关系字段而不是一个。
followerId
和followingId
是强制性的。当其中任何一个不存在时,拥有Follows
关系 table 并没有真正意义。 (没有一个用户关注和一个用户关注,你不能有关注关系)。@@id([followerId, followingId])
表示Follows
table中的主键。单独的id
字段是多余的。- 将字段名称更改为驼峰式命名,这是 Prisma 中推荐的约定。
4 是可选的当然,但我建议遵循它 none 少。
您可以在 Prisma 文档的 self-reation article 的多对多小节中找到更多详细信息。