我有一个创建用户函数在我的user.server.ts
:
export async function createUser(username: User["username"], email: User["email"], password: string) {
const hashedPassword = await bcrypt.hash(password, 10)
const user = await prisma.user.create({
data: {
email,
username,
role: {
create: {
name: ValidRoles["User"]
}
},
hashed_password: hashedPassword,
},
})
return prisma.userProfile.create({
data: {
user: {
connect: user
},
userId: user.id,
}
})
}
遵循Schema:
model User {
id Int @id @default(autoincrement())
username String @unique @default("user")
email String @unique
hashed_password String
role Role @relation(fields: [roleId], references: [id]) // Fields: PK, references: FK
roleId Int @default(0)
profile UserProfile @relation(fields: [profileId], references: [id], onUpdate: Cascade)
profileId Int @unique @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
}
model UserProfile {
id Int @id @default(autoincrement())
user User?
userId Int @unique
}
然而,当我注册一个新用户时,我得到这个错误:
Error:
Invalid `prisma.user.create()` invocation in
appmodelsuser.server.ts:18:34
15 export async function createUser(username: User["username"], email: User["email"], password: string) {
16 const hashedPassword = await bcrypt.hash(password, 10)
17
→ 18 const user = await prisma.user.create(
Foreign key constraint failed on the field: `User_profileId_fkey (index)`
at Zr.handleRequestError (node_modules@prismaclientruntimelibrary.js:171:6414)
at Zr.handleAndLogRequestError (node_modules@prismaclientruntimelibrary.js:171:5948)
at Zr.request (node_modules@prismaclientruntimelibrary.js:171:5786)
at t._request (node_modules@prismaclientruntimelibrary.js:174:10455)
at createUser (appmodelsuser.server.ts:18:16)
at action (approutesregister.tsx:26:9)
at Object.callRouteActionRR (buildserver.js:39464:20)
at callLoaderOrAction (buildserver.js:38586:18)
at submit (buildserver.js:38277:20)
at queryImpl (buildserver.js:38240:27)
我认为我的亲戚是正确的,如果他们不是,如果有人能详细说明,那就太好了。否则,如果没有,出了什么问题,我该如何补救?谢谢你的帮助。
profile UserProfile @relation(fields: [profileId], references: [id], onUpdate: Cascade)
profileId Int @unique @default(1)
你有profileId
作为NOT NULL
,默认为1
。如果你没有UserProfile
和1
的id
,那么数据库不会喜欢这个id指向一个不存在的记录。
也许你应该把它变成一个可空的引用,比如:
profileId Int? @unique