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

如何将Next.js生成的Prisma类型从snake_case转为camelCase

解决Prisma生成TS类型的蛇形转驼峰及非空设置问题

针对Next.js 12.3.0 + Prisma 4.5.0的全栈应用,要实现两个需求:将Prisma生成的TypeScript类型字段从蛇形命名(snake_case)转为驼峰命名(camelCase),同时将大部分字段设为非空类型(score字段保留可空),具体操作如下:

1. 配置命名规则实现蛇形列名转驼峰TS类型

在prisma/schema.prisma文件的generator块中添加命名规则配置,让Prisma自动将数据库的蛇形列名映射为前端的驼峰TS字段名:

generator client {
  provider        = "prisma-client-js"
  namingConvention = {
    model = "PascalCase"   // 生成的TS模型名用大驼峰(符合TS规范)
    field = "camelCase"    // 生成的TS字段用小驼峰
    column = "snake_case"  // 数据库列保持蛇形命名
  }
}

2. 修改模型字段设置非空

调整match模型的字段名(改为驼峰)并移除可空标识?(score字段除外),确保生成的TS类型非空:

model match {
  id            Int
  tournamentId  Int         // 移除?设为非空
  player1Id     Int
  player2Id     Int
  comment       String
  isCompleted   Boolean
  stage         Int
  startDate     DateTime @db.Date
  winnerId      String
  score         String?     // 保留可空
  player3Id     Int
  player4Id     Int
}

3. 重新生成Prisma客户端

运行以下命令更新生成的TS类型:

npx prisma generate

最终生成的TS类型

执行上述操作后,生成的TypeScript类型会符合预期:

export type Match = {
  id: number
  tournamentId: number
  player1Id: number
  player2Id: number
  comment: string
  isCompleted: boolean
  stage: number
  startDate: Date
  winnerId: string
  score: string | null
  player3Id: number
  player4Id: number
}

注意事项

  • 修改字段非空前,需确保数据库对应列没有NULL值,否则执行迁移命令会报错,可提前清理NULL数据或设置默认值。
  • 前端代码需同步改为使用驼峰字段名,替换原有的蛇形命名。

内容的提问来源于stack exchange,提问作者Maksim Hodasevich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:55:23