Search code examples
node.jstypescriptapiprisma

Can't disconnect relation of explicit many-to-many


I'm trying to delete some users which are related to a group.

Here is the schema:

model User {
  id    String @id @default(cuid())
  username String 
  email String @unique
  password String?

  group GroupUser[]

}

model Group {
  id    String @id @default(cuid())
  name String

  user GroupUser[]

}
        
model GroupUser{
  userId String
  user User @relation(fields: [userId],references: [id],onDelete: Cascade,onUpdate:Cascade)

  groupId String
  group Group @relation(fields: [groupId],references: [id],onDelete: Cascade,onUpdate: Cascade)

  @@id([userId,groupId])
}

The code to delete the users:

async deleteUsersFromGroup(id: string, userData: UpdateGroupDto): Promise<number> {
  const deletedUsers = await prisma.group.update({
  where: {
    id: id,
  },
  data: {
    user: { disconnect: /* trying to put the array of users id here */ },
  },
});
return deletedUsers.length;

}

The problem is that I want to give the userID inside of the disconnect but it is asking me for userId_groupId which is the relational key.


Solution

  • Since I wanted to delete multiple users at the same time I used the map function inside userId, resorting to prisma.groupUser.delete().

    async deleteUsersFromGroup(id: string, userData: DeleteGroupDto): Promise<any> {
           
        
            const response = await prisma.groupUser.deleteMany({
              where: {
                groupId: id,
                userId: { in: userData.users.map(user => user.userId) },
              },
            });
        
            return response.count
          }