Prisma How to automatically update "updatedAt" field of parent element when a child element is created or updated?

Viewed 1724

Let's say I have this schema:

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
}

Now what I want to archive is, if a user's profile is updated, for example, a bio field is updated, I want the updatedAt field on User model to automatically reflect that and get updated too to the current timestamp.

Any guide, hint or suggestion will be much appreciated!!

1 Answers

The easiest way would be to make some wrapper function I think, for example:

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