Prisma how do I save nested tables

Viewed 29

I don't even know if it's possible, but I'm trying to create two records simultaneously.

  model User {
  id      Int      @id @default(autoincrement())
  email   String   @unique
  name    String?
  role    Role     @default(USER)
  posts   Post[]
  profile Profile?
}

Let says I want to create a user and a profile in the same call, so if the user profile fails, I also wish the User creation will fail.

I can get the desired result if I make a User and await the user Id and Id to create the Profile, but that way, I'm writing twice to the database, and If the Profile fails, I can't roll back the User.

2 Answers

Yes, it's possible with Prisma, you can learn more here

For your schema, I can do nested write like this:

await prisma.profile.create({
  data: {
    avatar: 'image.png',
    address: 'somewhere'
    users: {
      create: {
        email: 'mail@test.com',
      }
    }
  }
})

When a nested query is being invoked, it's by default wrapped in a transaction, so in this case when user is created but there's an error in creating profile then the user would be automatically rolled back.

  await prisma.user.create({
    data: {
      email: 'test@test.com',
      name: 'Test'
      profile: {
        create: {
          reputation: 1,
        }
      }
    }
  })
Related