在 prisma create 上自动添加 UUID 关系

con*_*cus 13 postgresql node.js prisma

我的 Postgres 数据库中有一个User,UserProfilePost模型。和User相互依赖UserProfile。我正在尝试创建一个User自动创建 a 的UserProfile对象,但我似乎不知道如何自动假定User关系的 ID UserProfile,我正在使用 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
}
Run Code Online (Sandbox Code Playgroud)

询问

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,
    },
});
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我尝试使用create: {}来假设用户的 UUID,但它无法创建一个实际的UserProfile,只是一个User,这当然会破坏系统。

Rya*_*yan 0

这是在Prisma中添加关系的正确方法。您用来create添加关系,UUID 将自动添加到该记录中。您不需要做任何其他事情。我尝试了以下方法并且对我来说效果很好:

已添加条目

结果记录已创建