How can I disconnect via explicit many-to-many usi...
# orm-help
y
How can I disconnect via explicit many-to-many using a where clause? The following is not working:
Copy code
await prisma.user.update({
  where: { id: 1 },
  data: {
    userRoles: {
      deleteMany: {
        where: {
          role: {
            type: 'SOME_ROLE',
          },
        },
      },
    },
  },
})
n
Hey Yaakov 👋 Are you receiving any error? How does your User model look like> Did you have a look at the disconnect query?
y
@Nurul Disconnect does not seem to work with "explicit" many-to-many
Copy code
model User {
  id        Int         @id @default(autoincrement())
  userRoles UserRoles[] @relation("UserRelation")
}

model Role {
  id    Int         @id @default(autoincrement())
  type  String
  users UserRoles[] @relation("RoleRelation")
}

model UserRoles {
  id       Int  @id @default(autoincrement())
  user_id  Int
  user     User @relation("UserRelation", fields: [user_id], references: [id])
  role_id  Int
  role     Role @relation("RoleRelation", fields: [role_id], references: [id])
}
What I really want to do is update a user's roles WHERE type = 'SOME_ROLE'
n
So for updating the roles you want to first delete the existing ones in UserRoles and then add new ones? Is that the reason you are using nested deleteMany?
y
@Nurul Correct. Either delete and recreate or alter the existing UserRole records.
Thus far, this is the best I have that works.
Copy code
await prisma.$transaction([
  prisma.userRoles.deleteMany({
    where: {
      user_id: 1,
      role: { type: 'SOME_ROLE' },
    },
  }),

  prisma.user.update({
    where: { id: 1 },
    data: {
      userRoles: {
        create: {
          role: { connect: { name: 'Supervisor' } },
        },
      },
    },
  }),
]);
I have 2 issues with this implementation: 1. It is using 2 separately written queries wrapped inside a transaction. 2. The first query hits the userRoles table directly rather than joining from the user. Mapping tables are usually not queried this way.