You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Prisma中断开多对多关联关系?

解决Prisma显式多对多关联的断开问题

我之前在Stack Overflow上解决了Prisma中显式多对多关联的创建问题,通过Connect API成功批量关联用户和组,代码如下:

prisma.group.update({
  where: {
    id: groupId,
  },
  data: {
      users: {
        create: users.map((user) => ({
          user: { connect: { id: user.id } },
        })),
      },
    },
  include: { users: true },
});

但现在不知道怎么反向断开关联,尝试的代码无法生效:

prisma.group.update({
  where: {
    id: groupId,
  },
  data: {
      users: {
        delete: users.map((user) => ({
          user: { disconnect: { id: user.id } },
        })),
      },
    },
  include: { users: true },
});

正确的断联方法

针对Prisma的显式多对多关联,有两种可靠的断联方式:

方式一:通过关联字段直接断开

使用disconnect操作替代错误的delete,语法如下:

prisma.group.update({
  where: { id: groupId },
  data: {
    users: {
      // 单个用户断开
      // disconnect: { id: userId }
      // 多个用户批量断开
      disconnect: users.map(user => ({ id: user.id }))
    }
  },
  include: { users: true }
});

方式二:直接操作中间关联表

如果你的显式多对多有对应的中间表模型(比如GroupUser),可以直接删除中间表的关联记录,这种方式更直观:

prisma.groupUser.deleteMany({
  where: {
    groupId: groupId,
    userId: { in: users.map(user => user.id) }
  }
});

错误原因说明

你之前的代码错误在于使用了delete操作来处理关联断开,并且嵌套了disconnect语法——这不符合Prisma的关联操作规范。delete用于删除模型本身的记录,而断开关联应该使用disconnect(针对关联字段)或直接删除中间表记录。

内容的提问来源于stack exchange,提问作者dpstudio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:45:37