如何在Prisma中使多对多关系表的followers和following字段可为空?
解决User模型中followers和following字段设为可为空的问题
要将你的Prisma模型里User的followers和following字段设置为可为空,只需在数组类型后添加?标记即可,修改后的完整模型代码如下:
model User { @@map("user") id Int @id @default(autoincrement()) firstName String @map("first_name") lastName String @map("last_name") followers Follows[]? @relation("following") following Follows[]? @relation("followers") } model Follows { @@id([followerId, followingId]) followerId Int followingId Int follower User @relation("followers", references: [id], fields: [followerId]) following User @relation("following", references: [id], fields: [followingId]) status FollowStatus }
关键说明:
- 在Prisma中,数组类型的关系字段默认在无关联记录时会返回空数组而非null;添加
?标记后,该字段明确允许返回null(同时仍支持空数组),满足你设置可为空的需求。 - 关联表
Follows中的followerId和followingId作为复合主键的一部分,依然保持必填状态——这确保每条关注记录必须关联两个有效用户,和User模型中字段的可为空设置互不冲突,只是允许单个用户没有关注者或关注对象的场景。
内容的提问来源于stack exchange,提问作者Nao COMATSU
相关产品推荐
相关产品推荐

