using prisma, how do you access newly created record from within a nested write (update first, then create within)

Viewed 1942

Using Prisma, I have a question about accessing a record that was newly created from within a nested write (update first, then create within).

I'm following along the examples on this page in the prisma docs.

In particular, I am looking at the following two items in the data model:

Note, I have slightly modified the example for the purposes of this question by adding a counter to User.

model User {
  id       Int     @id @default(autoincrement())
  email    String  @unique
  posts    Post[]
  counter  Int
}
model Post {
  id         Int      @id @default(autoincrement())
  title      String
  author     User?    @relation(fields:  [authorId], references: [id])
  authorId   Int?
}

Now, let's say you want to create a new Post and connect it to the User and at the same time, you also want to increment the counter.

My assumption, after reading this section of the doc is that you would need to update the existing User and within that, create a new Post record.

i.e.

const user = await prisma.user.update({
  where: { email: 'alice@prisma.io' },
  data: {
    // increment the counter for this User
    counter: {
      increment: 1,
    },
    // create the new Post for this User
    posts: {
      create: { title: 'Hello World' },
    },
  },
})

My question is this. In the above scenario, how do you access the newly created Post in the return of the query?

In particular, say you want to get the id of the new Post?

From what I can tell, the returned user object could possibly include the array of all associated Posts, i.e. if you added this to the update query...

include: {
  posts: true,
}

But I can't yet see how, using Prisma, you get the individual Post that you just created as part of this update query.

1 Answers

I have found one way of achieving this that works.

It uses the tranaction api.

Basically, instead of trying to use a nested write that begins with an update on User and contains a nested create on Post...

I split the two operations out into separate variables and run them together using a prisma.$transaction() as follows.

const updateUser = prisma.user.update({
  where: { email: 'alice@prisma.io' },
  data: {
    // increment the counter for this User
    counter: {
      increment: 1,
    },
  },
});

const createPost = prisma.post.create({
  data: {
    // create the new Post for this User
    title: 'Hello World',
    author: {
      connect: {
        email: 'alice@prisma.io',
      },
    },
  },
});

const [ updateUserResult, createPostResult ] = await prisma.$transaction([updateUser, createPost ]);

// if createPostResult, then can access details of the new post from here...
Related