Update multiple tables in one query

2.5k views Asked by At

I couldn't find any relevant info on Prisma docs, nor on SO on this question.

My relevant schema looks like this:

model User {
  id             Int       @default(autoincrement()) @id
  createdAt      DateTime  @default(now())
  updatedAt      DateTime  @updatedAt
  firstName      String?
  lastName       String?
  email          String    @unique
  hashedPassword String?
  role           String    @default("user")
  sessions       Session[]
  profile        Profile?
}

model Profile {
  id                 Int       @default(autoincrement()) @id
  aboutMe            String?
  location           String?
  profession         String?
  user               User      @relation(fields:[userId], references: [id])
  userId             Int
}

I want to update multiple columns in both tables however, have been unable to get the mutation to work in Prisma. So, this is what my mutation looks like at the moment:

 ...
  const {aboutMe, location, profession, firstName, lastName } = inputs;
  const profile = await db.user.update({
    where: { id: ctx.session!.userId },
    data: {
      profile: {
        update: {
          aboutMe,
          location,
          profession,
        },
      },
    },
  });
  const user = await db.user.update({
    where: { id: ctx.session!.userId },
    data: {
      firstName,
      lastName,
    },
  });
...

As you can see, I have two mutations, is it possible the update multiple tables with a single mutation?

Thank you.

1

There are 1 answers

0
Ryan On BEST ANSWER

This should work:

const profile = await db.user.update({
    where: { id: u.id },
    data: {
      firstName: 'name',
      lastName: 'name',
      profile: {
        update: {
          aboutMe: 'aboutMe',
          location: 'aboutMe',
          profession: 'aboutMe',
        },
      },
    },
    include: { profile: true },
  })