TKTheTechie
TKTheTechie

Reputation: 103

Updating a many-to-many relationship in Prisma

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.

Upvotes: 8

Views: 30095

Answers (1)

Ryan
Ryan

Reputation: 6327

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.

Upvotes: 12

Related Questions