在 Prisma 中更新多对多关系

Updating a many-to-many relationship in Prisma

我正在尝试找出实现以下架构的 upsert/update 的正确方法:

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

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

这是我想做的。获取附加了类别 ID 的 post 并将其插入到上面的架构中。

出现以下命令插入post

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

我的挑战是如何同时更新类别。我将获得类似 1、2、3 的类别列表,如果它们不存在,我需要将其插入类别 table 并向其添加 post。如果该类别确实存在,我需要使用我在上面插入的 post 更新记录,保留所有附加的 posts.

如果能指出正确的方向,我将不胜感激。

对于模型,可以简化如下,因为Prisma支持@updatedAt会自动更新列:

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

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

至于查询,它看起来像这样:

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 将创建(如果不存在)并将类别添加到帖子中。