Updating a many-to-many relationship in Prisma

Viewed 10465

I'm trying to figure out the right way to implement an upsert/update of the following schema:

model Post {
  author     String @Id
  lastUpdated DateTime   @default(now())
  categories Category[]
}

model Category {
  id     Int     @id 
  posts  Post[]
}

Here is what I'd like to do. Get a post with category ids attached to it and insert it into the schema above.

The following command appears to insert the post

     const post = await prisma.post.upsert({
         where:{
              author: 'TK' 
         },
         update:{
             lastUpdated: new Date()
         },
         create: {
             author: 'TK'
         }})

My challenge is how do I also upsert the Category. I'll be getting a list of Catogories in the like 1,2,3 and if they do not exist I need to insert it into the category table and add the post to it. If the category does exist, I need to update the record with the post I inserted above preserving all attached posts.

Would appreciate it if I could be pointed in the right direction.

1 Answers

For the model, it can be simplified as follows as Prisma supports @updatedAt which will automatically update the column:

model Post {
  author      String     @id
  lastUpdated DateTime   @updatedAt
  categories  Category[]
}

model Category {
  id    Int    @id
  posts Post[]
}

As for the query, it would look like this:

const categories = [
  { create: { id: 1 }, where: { id: 1 } },
  { create: { id: 2 }, where: { id: 2 } },
]
await db.post.upsert({
  where: { author: 'author' },
  create: {
    author: 'author',
    categories: {
      connectOrCreate: categories,
    },
  },
  update: {
    categories: { connectOrCreate: categories },
  },
})

connectOrCreate will create if not present and add the categories to the posts as well.

Related