Prisma 如何在创建或更新子元素时自动更新父元素的“updatedAt”字段?

Sha*_*eed 8 backend node.js server prisma

假设我有这个架构:

model User {
   id String @id @default(cuid())
   name String
   email String
   profile Profile?
   createdAt DateTime @default(now())
   updatedAt DateTime @updatedAt
}

model Profile {
   id Int @id @default(autoicrement())
   bio String?
   avatar String?
   user User @relation(fields: [userId], references: [id], onDelete: Cascade)
   userId String @unique
}
Run Code Online (Sandbox Code Playgroud)

现在我想要存档的是,如果用户的个人资料被更新,例如,字段bio被更新,我希望模型updatedAt上的字段User自动反映这一点并更新到当前时间戳。

任何指导、提示或建议将不胜感激!

Dan*_*ila 8

我认为最简单的方法是制作一些包装函数,例如:

const updateUserProfile = (id, data) => {
  return prisma.profile.update({
    where: {
      id
    },
    data: {
      ...data,
      user: {
        update: {
          updatedAt: new Date()
        }
      }
    }
  })
}
Run Code Online (Sandbox Code Playgroud)