简体   繁体   中英

Disconnecting a Many to Many Relation in Prisma

So, I asked this question yesterday and a user on here was kind enough to point me in the right direction when using explicit many-to-many relations in Prisma.

From that accepted answer I was able to update the relation using the Connect API.


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

There was a slight issue with the implementation when connecting the relations in a loop, but I corrected that and made an edit to update the accepted answer with the correct code as shown below:


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

What I can't seem to figure out now is how I do the reverse and 'disconnect' the relation in a similar way. I'd be grateful for some help on this.

I've tried something like the following that I thought might work:

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

With explicit many-to-many relation you can just delete from the table that represents the relation (ie UsersGroups in your case):

prisma.usersGroups.delete({
  where: { userId_groupId: { groupId: groupId, userId: userId } },
});

If you want to delete multiple users from a group:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM