You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:02:46