0

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 },
});
dpstudio
  • 147
  • 3
  • 10

2 Answers2

4

With explicit many-to-many relation you can just delete from the table that represents the relation (i.e. 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) } },
});
some-user
  • 3,888
  • 5
  • 19
  • 43
1

This post is the top search result for both implicit and explicit disconnect many to many. If you want to completely disconnect an implicit many to many:

const data = await prisma.group.update({
    where: {
        id: groupId,
    },
    data: {
        users: {
            set: [],
        },
    },
});

Gotten from here: https://github.com/prisma/prisma/issues/5946

Michael Eliot
  • 831
  • 8
  • 18