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.
CodePudding user response:
You would need to delete the record from the connecting table i.e. GroupUser
.
You can try something like this:
await prisma.groupuser.delete({
where: {
userId_groupId: {
userId: 'userId',
groupId:'groupId'
}
}
});
If the connecting records are deleted then both the entities would be disconnected.
CodePudding user response:
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
}