ค้นหาเว็บไซต์

javascript - ฉันจะสร้างความสัมพันธ์แบบ 1 ต่อ 1 ที่จำเป็นโดยใช้ Prisma ได้อย่างไร?


ฉันต้องการสร้างผู้ใช้ โดยมีรหัสที่กำหนดไว้ล่วงหน้า และสร้างสิทธิ์และโปรไฟล์ที่เชื่อมโยงกับผู้ใช้นั้นแบบเป็นธุรกรรมโดยใช้การเขียนซ้อน แต่ตัวคอมไพเลอร์ TypeScript แจ้งว่าฉันสามารถสร้างวัตถุซ้อนเท่านั้น หากฉันไม่ระบุรหัสที่กำหนดไว้ล่วงหน้า หรือถ้าฉันระบุรหัสแล้ว ฉันจะไม่สามารถสร้างวัตถุที่เชื่อมโยงได้

// 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'.

ฉันจะไปสร้างวัตถุทั้งหมดเหล่านี้โดยใช้การเขียนแบบซ้อนด้วยรหัสที่กำหนดไว้ล่วงหน้าได้อย่างไร?

ป.ล.: นอกจากนี้ ดูเหมือนว่าฉันต้องทำซ้ำ userId บนวัตถุ create ด้วย ซึ่งฉันคิดว่าควรถูกสรุปได้โดยอัตโนมัติ ฉันไม่แน่ใจว่านี่ถูกต้องหรือไม่

ฉันซาบซึ้งในความรู้ใด ๆ ที่คุณอาจจะแบ่งปัน