Prisma迁移提示新增必填列followingId无默认值该如何修复?
报错原因
你遇到的报错核心和id字段的默认值无关,触发原因如下:
Step 2 Added the required column
followingIdto theUserToUsertable without a default value. There are 2 rows in this table, it is not possible to execute this step.
当前你的数据库中UserToUser表已经存在2条历史数据,本次建模修改新增了必填非空的followingId字段,但你没有给现有数据的该字段指定填充值,数据库无法处理必填字段的空值情况,因此迁移执行中断。
修复方案
方案1:开发环境可丢弃测试数据(推荐开发阶段使用)
如果是本地开发环境,不需要保留现有测试数据,直接重置迁移即可:
- 删除
prisma/migrations文件夹下本次生成的未执行成功的迁移文件 - 执行重置命令:
npx prisma migrate reset
该操作会清空数据库所有数据,重新执行所有迁移,不会存在旧数据空值冲突问题。
方案2:需要保留现有数据的处理方式
如果是生产环境或者需要保留现有2条数据,按以下步骤操作:
- 先将
followingId字段暂时改为可选,修改模型定义:
model UserToUser { id Int @id @default(autoincrement()) userId Int? follower User? @relation("follower",fields: [userId], references: [id]) following User? @relation("following", fields: [followingId], references: [id]) followingId Int? // 先设置为可选 }
- 执行迁移生成可选字段的迁移文件:
npx prisma migrate dev,此时字段允许为空,现有数据不会触发报错。 - 手动给现有2条
UserToUser数据补充正确的followingId有效值,保证所有数据的该字段都不为空。 - 再把模型改回原来的必填设置:
model UserToUser { id Int @id @default(autoincrement()) userId Int? follower User? @relation("follower",fields: [userId], references: [id]) following User @relation("following", fields: [followingId], references: [id]) followingId Int // 改回必填 }
- 再次执行迁移:
npx prisma migrate dev,此时所有数据都有合法的followingId值,可正常执行完成。
方案3:临时设置默认值(仅适用于你能确定默认值合法的场景)
如果可以给现有数据统一设置一个合法的默认followingId(比如对应一个测试用户的id),也可以直接在字段上临时加默认值,迁移完成后再删除默认值即可:
followingId Int @default(1) // 1替换为你数据库中真实存在的合法用户id
执行迁移完成后再移除@default配置即可。
内容的提问来源于stack exchange,提问作者Kyro X
相关产品推荐
相关产品推荐

