我的Postgres数据库中有一个User
、UserProfile
和Post
模型。User
和UserProfile
相互依赖。我正在尝试创建一个User
,用它自动创建一个UserProfile
,但我似乎找不出如何为UserProfile
关系自动假定User
的ID,而是使用UUID作为User
模型。
模式模型
model User {
id String @id @default(uuid())
createdAt DateTime @default(now())
username String @unique @db.VarChar(20)
emailEncrypted String @unique
emailIv String @unique
password String
isMod Boolean @default(false)
isAdmin Boolean @default(false)
emailConfirmed Boolean @default(false)
profile UserProfile?
}
model UserProfile {
user User @relation(fields: [id], references: [id])
id String @unique
posts Post[]
comments Comment[]
}
model Post {
id String @id @default(uuid())
createdAt DateTime @default(now())
title String @db.VarChar(300)
caption String @db.VarChar(1000)
upvotes Int @default(0)
downvotes Int @default(0)
comments Comment[]
author UserProfile @relation(fields: [authorId], references: [id])
authorId String
}
查询
const user = await prisma.user.create({
data: {
username,
emailEncrypted: encrypted,
emailIv: iv,
password: hashedPassword,
profile: {
create: {}, // create a UserProfile that assumes the created user's UUID as a relation
},
},
select: {
id: true,
},
});
正如您所看到的,我尝试使用create: {}
来假设用户的UUID,但是它无法创建一个实际的UserProfile
,只是一个User
,这当然会破坏系统。
发布于 2021-07-04 10:11:22
我也查过这个。为了在创建用户之后包含profile
数据,我做了以下调整。
const user = await prisma.user.create({
data: {
username: "username",
emailEncrypted: "encrypted",
emailIv: "iv",
password: "hashedPassword",
profile: {
create: {},
},
},
select: {
id: true,
createdAt: true,
emailConfirmed: true,
emailIv: true,
emailEncrypted: true,
isAdmin: true,
isMod: true,
password: true,
profile: true,
username: true,
},
});
这输出,
没问题,效果很好。
还在想你面临的问题是什么。
你能粘贴错误日志吗?
发布于 2021-06-22 04:53:40
这是在普里斯马增加关系的正确方式。使用create
添加关系,UUID将自动添加到该记录中。你不需要做任何其他的事。我尝试了以下几种方法,效果很好:
https://stackoverflow.com/questions/68045139
复制相似问题