javascript - 我如何使用 Prisma 建立一個必需的 1 對 1 關係?
我想建立一個使用者,使用預先定義的 ID,並透過巢狀寫入交易性地建立與使用者連結的授權與個人資料。但 TypeScript 編譯器抱怨說,只有在我不提供預先定義的 ID 時,我才能建立巢狀物件。或者,如果我提供了 ID,就不能建立連結的物件。
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model User {
id String
emailAddress String
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
objectId String @id @default(auto()) @map("_id") @db.ObjectId
profile UserProfile @relation(fields: [id], references: [userId])
authentication UserAuthentication @relation(fields: [id], references: [userId])
@@unique([id])
@@unique([emailAddress])
@@map("users")
}
model UserProfile {
firstName String
lastName String
userId String
objectId String @id @default(auto()) @map("_id") @db.ObjectId
user User?
@@unique([userId])
@@map("user-profiles")
}
model UserAuthentication {
passwordHash String
userId String
objectId String @id @default(auto()) @map("_id") @db.ObjectId
user User?
@@unique([userId])
@@map("user-auths")
}
context.prisma.user
.create({
data: {
id: userId,
emailAddress: input.emailAddress.toLowerCase(),
profile: {
create: {
userId,
firstName: input.firstName,
lastName: input.lastName
}
},
authentication: {
create: {
userId,
passwordHash
}
},
createdAt,
updatedAt: createdAt
}
})
類型編譯器報錯,顯示 id 或 authentication/profile 為 Type 'xxx' is not assignable to type 'never'。
我該如何使用帶有預定義 ID 的嵌套寫入來創建所有這些對象?
附言:看起來,我還必須在 create 對象上重複 userId,我本以為這可以被推斷出來。我不知道這是否正確。
我感謝你可能分享的任何知識。