【问题标题】:Prisma How to automatically update "updatedAt" field of parent element when a child element is created or updated?Prisma 如何在创建或更新子元素时自动更新父元素的“updatedAt”字段?
【发布时间】:2022-01-21 18:59:28
【问题描述】:

假设我有这个架构:

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
}

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

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

【问题讨论】:

    标签: node.js server backend prisma


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 2019-09-18
      • 1970-01-01
      • 2019-02-06
      相关资源
      最近更新 更多