如何为含嵌套结构与字符串数组的产品建模Prisma Schema
适配SQL Server的Prisma Schema建模方案(对应复杂嵌套与数组属性)
错误根源分析
- 原模型将
location和images定义为数组类型(Location[]、Images[]),但目标结构中每个产品对应单个嵌套对象,关联关系匹配错误。 - SQL Server不支持Prisma的原生原始类型列表(如
String[]),必须通过Json类型模拟数组结构。
方案一:用Json类型贴合目标嵌套结构
该方案直接用Json类型存储嵌套对象和数组,完全匹配你给出的Product接口结构:
generator client { provider = "prisma-client-js" } datasource db { provider = "sqlserver" url = env("DATABASE_URL") relationMode = "prisma" } model Product { id Int @id @default(autoincrement()) name String description String price Float rating Float category String retailer String location Location? @relation(fields: [locationId], references: [id]) locationId Int? @unique images Images? @relation(fields: [imagesId], references: [id]) imagesId Int? @unique createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Location { id Int @id @default(autoincrement()) name String coordinates Json // 存储{ longitude: number, latitude: number }格式的JSON productId Int @unique product Product @relation(fields: [productId], references: [id]) } model Images { id Int @id @default(autoincrement()) thumbnail String content Json // 存储字符串数组,如["url1", "url2"] productId Int @unique product Product @relation(fields: [productId], references: [id]) }
核心说明
Product与Location、Images采用一对一关联(通过@unique标记外键字段),匹配目标结构的单个嵌套对象要求。Location.coordinates和Images.content使用Json类型,SQL Server会自动映射为带JSON约束的NVARCHAR(MAX)字段,支持存储嵌套对象和数组。- 可选的
?标记允许嵌套结构为空,可根据业务需求移除。
方案二:拆分嵌套字段为数据库列(关系型设计风格)
若倾向于关系型数据库范式设计,可将嵌套字段拆分为独立列,查询时通过Prisma构造目标嵌套结构:
generator client { provider = "prisma-client-js" } datasource db { provider = "sqlserver" url = env("DATABASE_URL") relationMode = "prisma" } model Product { id Int @id @default(autoincrement()) name String description String price Float rating Float category String retailer String location Location? @relation(fields: [locationId], references: [id]) locationId Int? @unique images Images? @relation(fields: [imagesId], references: [id]) imagesId Int? @unique createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Location { id Int @id @default(autoincrement()) name String longitude Float latitude Float productId Int @unique product Product @relation(fields: [productId], references: [id]) } model Images { id Int @id @default(autoincrement()) thumbnail String content Json // 字符串数组仍需用Json存储,SQL Server无原生字符串数组类型 productId Int @unique product Product @relation(fields: [productId], references: [id]) }
查询示例(构造目标嵌套结构)
通过Prisma的select方法,可直接返回符合目标接口的嵌套数据:
const product = await prisma.product.findUnique({ where: { id: 1 }, select: { id: true, name: true, description: true, price: true, rating: true, category: true, retailer: true, location: { select: { name: true, coordinates: { longitude: true, latitude: true } } }, images: { select: { thumbnail: true, content: true } }, createdAt: true, updatedAt: true } });
内容的提问来源于stack exchange,提问作者user20983853
相关产品推荐
相关产品推荐

