NestJS-Prisma 如何使用关系字段创建记录?
Posted
技术标签:
【中文标题】NestJS-Prisma 如何使用关系字段创建记录?【英文标题】:NestJS-Prisma How to create record with relational fields? 【发布时间】:2022-01-04 22:17:55 【问题描述】:我是 NestJS 和 Prisma 的初学者。
我正在尝试创建一个用户,我的表有带有表地址的关系字段。 要创建用户,我需要先在地址表中添加一个寄存器,以便在我的用户表上使用 adress_id。
我收到此错误:
这是我的代码
服务:
async create(createUserDto: CreateUserDto)
const hash = crypto.SHA256(createUserDto.password);
const passwordHash = (hash.toString(crypto.enc.Hex).toUpperCase());
const createCategory = await this.client.user.create(
data:
name: createUserDto.name,
email: createUserDto.email,
age: createUserDto.age,
password: passwordHash,
roleId: createUserDto.roleId,
address:
create: [
street: createUserDto.address.street,
number: createUserDto.address.number,
complement: createUserDto.address.complement,
neighborhood: createUserDto.address.neighborhood,
cityId: createUserDto.address.cityId,
stateId: createUserDto.address.stateId,
zipcode: createUserDto.address.zipcode
,
],
,
,
)
DTO:
export class CreateUserDto
readonly id: number
readonly name :string
readonly age :any
readonly email :any
readonly password :any
readonly roleId :any
readonly addressId: number
readonly address:
street: string,
number: number,
complement: string,
neighborhood: string,
cityId: number,
stateId: number,
zipcode: string
Schema.prisma
model user
id Int @id @default(autoincrement())
name String
age Int
email String @unique
password String
roleId Int
role role @relation(fields: [roleId], references: [id])
addressId Int
address addresses @relation(fields: [addressId], references: [id])
model addresses
id Int @id @default(autoincrement())
street String
number String
complement String
neighborhood String
cityId Int
city cities @relation(fields: [cityId], references: [id])
stateId Int
state state @relation(fields: [stateId], references: [id])
zipcode String
user user[]
我做错了什么? 谢谢!
【问题讨论】:
【参考方案1】:您的address.create
语法错误。 User-Address 是one-to-many
关系,所以一个用户只能有一个地址。所以address.create
应该传递一个address
对象,而不是一个数组。
这应该可以正常工作
const createCategory = await this.client.user.create(
data:
name: createUserDto.name,
email: createUserDto.email,
age: createUserDto.age,
password: passwordHash,
roleId: createUserDto.roleId,
address:
create:
street: createUserDto.address.street,
number: createUserDto.address.number,
complement: createUserDto.address.complement,
neighborhood: createUserDto.address.neighborhood,
cityId: createUserDto.address.cityId,
stateId: createUserDto.address.stateId,
zipcode: createUserDto.address.zipcode
,
,
,
)
【讨论】:
以上是关于NestJS-Prisma 如何使用关系字段创建记录?的主要内容,如果未能解决你的问题,请参考以下文章