Here's the syntax for queries with composite key

    const deleteRelation = await prisma.labelplaylist.delete({
        where: {
            playlistId_labelId: {
                playlistId: playListIdVariable, //replace with appropriate variable
                labelId: labelIdVariable, //replace with appropriate variable
            },
        },
    });

You can read more in the get record by compound ID or compound unique identifier subsection of the CRUD Reference Guide in the Prisma docs. This reference shows reading data, but the where condition is similar for delete and update as well.

Answer from Tasin Ishmam on Stack Overflow
🌐
GitHub
github.com › prisma › prisma › discussions › 10459
how to delete rows from a many-to-many relation table ONLY · prisma/prisma · Discussion #10459
model menuitem { id String @id @default(uuid()) name String @db.VarChar(100) price Float menu_category menu_category @relation(fields: [category_id], references: [id], onDelete: Cascade, map: "menuitem_ibfk_1") menuitem_variation menuitem_variation[] } model menuitem_variation { id String @id @default(uuid()) menuitem_id String variation_id String menuitem menuitem @relation(fields: [menuitem_id], references: [id], onDelete: Cascade, map: "menuitem_variation_ibfk_1") variation variation @relation(fields: [variation_id], references: [id], onDelete: Cascade, map: "menuitem_variation_ibfk_2") } m
Author   prisma
🌐
GitHub
github.com › prisma › prisma › discussions › 19337
How to disconnect model in many to many relation on delete · prisma/prisma · Discussion #19337
Then I used transaction and first updated the Material and remove the Tag connection and deleted it. const [, material] = await prisma.$transaction([ prisma.material.update({ where: { id, }, data: { tags: { disconnect: materialTags.map((materialTag) => ({ id: materialTag.id, })), }, }, }), prisma.material.delete({ where: { id, }, }), ]);
Author   prisma
Discussions

mysql - Prisma delete many to many relationship with Composite Key - Stack Overflow
You can read more in the get record ... in the Prisma docs. This reference shows reading data, but the where condition is similar for delete and update as well. ... Sign up to request clarification or add additional context in comments. ... Since it's an explicit many-to-many relationship, nested deleteMany ... More on stackoverflow.com
🌐 stackoverflow.com
prisma - How to delete a record and any relationship records in an explicit many to many relationship? - Stack Overflow
I'm struggling to find documentation for handling explicit many to many relationships in Prisma. So I have resorted to dev by Stackoverflow.... I have a many to many relationship: model Fight { i... More on stackoverflow.com
🌐 stackoverflow.com
Disconnecting a Many to Many Relation in Prisma - Stack Overflow
Gotten from here: https://github.com/prisma/prisma/issues/5946 ... Sign up to request clarification or add additional context in comments. ... Save this answer. ... Show activity on this post. With explicit many-to-many relation you can just delete from the table that represents the relation (i.e. More on stackoverflow.com
🌐 stackoverflow.com
postgresql - Prisma Explicit Many to Many - how to delete item without deleting user - Stack Overflow
My use case is simple: There's users Users can create workspaces Users can delete workspaces User gets a role on each workspace (OWNER, ADMIN, MANAGER, VIEWER) The problem: This requires an expli... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Substack
shazaali.substack.com › shaza’s substack › prisma: a comprehensive guide to managing relationships with set, deletemany, and disconnect
Prisma: A Comprehensive Guide to Managing Relationships with set, deleteMany, and disconnect
October 20, 2024 - You can delete multiple records from the related table using deleteMany. This is useful when you want to delete posts that match certain criteria. // Delete all posts of the user await this.prisma.post.deleteMany({ where: { userId: 1 } // Delete ...
Top answer
1 of 2
5

Here is the Prisma documentation to disconnect related fields

For single disconnect

const updatePost = await prisma.user.update({
  where: {
    id: 16,
  },
  data: {
    posts: {
      disconnect: [{ id: 12 }, { id: 19 }],
    },
  },
  select: {
    posts: true,
  },
})

To disconnect all

const updateUser = await prisma.user.update({
  where: {
    id: 16
  },
  data: {
    posts: {
      set: []
    }
  },
  include: {
    posts: true
  }
})
2 of 2
2

here you go a way to do that:

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

const saveData = async () => {
  const fighter1 = await prisma.fighter.create({
    data: {
      name: 'Ryu',
    },
  })
  const fighter2 = await prisma.fighter.create({
    data: {
      name: 'Ken',
    },
  })
  console.log('FIGHTERS');
  console.log(JSON.stringify(fighter1, null, 2));
  console.log(JSON.stringify(fighter2, null, 2));

  const fight = await prisma.fight.create({
    data: {
      name: 'Ryu vs Ken',
      fighters: {
        createMany: {
          data: [
            {
              fighterId: fighter1.id,
            },
            {
              fighterId: fighter2.id,
            },
          ]
        },
      },
    },
    select: {
      id: true,
      fighters: {
        select: {
          fighter: true,
        },
      },
    },
  });
  console.log('FIGHTS');
  console.log(JSON.stringify(await prisma.fight.findMany({ include: { fighters: true } }), null, 2));

  const fighterFightsToDelete = prisma.fighterFights.deleteMany({
    where: {
      fightId: fight.id,
    }
  })

  const fightToDelete = prisma.fight.delete({
    where: {
      id: fight.id,
    }
  })

  await prisma.$transaction([ fighterFightsToDelete, fightToDelete ])
  console.log('RESULT');
  console.log(JSON.stringify(await prisma.fight.findMany({ include: { fighters: true } }), null, 2));
  console.log(JSON.stringify(await prisma.fighter.findMany({ include: { fights: true } }), null, 2));
}

saveData()

And the result is the following :)

🌐
GitHub
github.com › prisma › prisma › discussions › 16204
Delete several explicit m:n relationship rows in update · prisma/prisma · Discussion #16204
(Delete the rows in the relational table) The problem is that when I'm trying to use the disconnect, it asks me for the relational key (groupId_userId) when I wanted to put the userId only. Maybe I should use another function but I'm not sure. ... async deleteUsersFromGroup(id: string, userData: DeleteGroupDto): Promise<any> { const response = prisma.group.update({ where: { id: id, }, data: { user: { disconnect: /* Trying to insert here the array of user's id (userData) */ }, }, include: { user: true }, }); return response; }
Author   prisma
Find elsewhere
🌐
Tericcabrel
blog.tericcabrel.com › many-to-many-relationship-prisma
Handle a Many-to-Many relationship with Prisma and Node.js
February 26, 2024 - import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient({ errorFormat: 'pretty' }); const main = async () => { const movieAvatar = await prisma.movie.findUniqueOrThrow({ where: { name: 'Avatar' } }); const userBob = await prisma.user.findUniqueOrThrow({ where: { email: 'bob@email.com' } }); // Delete 'Avatar' rating made by Bob await prisma.movieRating.delete({ where: { movieId_userId: { movieId: movieAvatar.id, userId: userBob.id, }, }, }); // Delete all the ratings for the movie 'Avatar' await prisma.movieRating.deleteMany({ where: { movieId: movieAvatar.id, }, }); }; main().then(); You can find this code in the file src/retrieve-data.ts. We saw how to manage a Many-to-Many relationship with Prisma, making it easy for developers to define entities and perform database queries using TypeScript code.
🌐
Answer Overflow
answeroverflow.com › m › 1081527405803491369
Prisma schema delete many to many - Theo's Typesafe Cult
March 4, 2023 - Hi, I have some troubles deleting a many to many relationship / data. Currently it says: ```ts prisma:error Invalid `prisma.templateTag.deleteMany()` invocation: Foreign key constraint failed on the field: `TagsOnTemplate_tagId_fkey (index)` ❌ tRPC failed on template.delete: Invalid `prisma.templateTag.deleteMany()` invocation: Foreign key constraint failed on the field: `TagsOnTemplate_tagId_fkey (index)` ``` This is the related schema: ```ts model TemplateTag { id String @id @default(cuid()) tag String @unique templates TagsOnTemplate[] } model Template { id String @id @default(cuid()) nam
🌐
GitHub
github.com › prisma › prisma › issues › 2328
Cascade deletes doesn't work on many to many relations · Issue #2328 · prisma/prisma
April 29, 2020 - Bug description I'm getting an error when I try to remove an entity from a explicit many-to-many relationship. The change you are trying to make would violate the required relation 'ContactToServerToServer' between the ContactToServerand...
Author   prisma
🌐
DEV Community
dev.to › this-is-learning › its-prisma-time-delete-4036
It's Prisma Time - Delete - DEV Community
January 5, 2022 - As you can see, you can do every type of check in you delete using the deleteMany and I think the definition types created by the Prisma team are a good friends to prevent errors. It's obvious that they don't create the right query for you, that's your work.
🌐
GitHub
github.com › prisma › prisma › issues › 16979
Allow use of multiple compound ids in `deleteMany()` or `findMany()` · Issue #16979 · prisma/prisma
December 22, 2022 - I have an explicite many-to-many relation (with a compound id) and I want to delete multiple relations. model CategoriesOnPosts { post Post @relation(fields: [postId], references: [id]) postId Int // relation scalar field (used in the `@relation` attribute above) category Category @relation(fields: [categoryId], references: [id]) categoryId Int // relation scalar field (used in the `@relation` attribute above) @@id([postId, categoryId]) } ... await prisma.$transaction(ids.map((id) => prisma.categoriesOnPosts.delete({ where: { postId_categoryId: id } }))
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 16390
Prisma Client: When `relationMode="prisma"` Deleting an item in an Implicit Many-to-Many does not delete the corresponding entry in the implicit pivot table · Issue #16390 · prisma/prisma
November 21, 2022 - async delete(id: number) { return await prisma.item.delete({ where: { id } }); } await delete(1); ... bug/2-confirmedBug has been reproduced and confirmed.Bug has been reproduced and confirmed.kind/bugA reported bug.A reported bug.topic: implicit ...
Author   prisma
🌐
Prisma
prisma.io › home › referential actions › referential actions › referential actions › referential actions › referential actions
Special rules for referential actions in SQL Server and MongoDB | Prisma Documentation
For this reason, when you set postgres as the database provider in the (default) foreignKeys relation mode, Prisma ORM warns users to mark as optional any fields that are included in a @relation attribute with a SetNull referential action. For all other database providers, Prisma ORM rejects the schema with a validation error. Restrict is not available for SQL Server databases, but you can use NoAction instead. onDelete: Cascade Deleting a referenced record will trigger the deletion of referencing record.
🌐
Stack Overflow
stackoverflow.com › questions › 73210720 › invalid-prisma-courseenrollment-delete-many-to-many-relation-in-prisma
reactjs - Invalid prisma.courseEnrollment.delete() many to many relation in prisma - Stack Overflow
August 2, 2022 - const student = await prisma.courseEnrollment.deleteMany({ where: { studentId: 58 } }) const studentToDelete = await prisma.student.delete({ where: { id: 58 } })
🌐
Reddit
reddit.com › r/supabase › [prisma] on delete cascade and related issues
r/Supabase on Reddit: [Prisma] ON DELETE CASCADE and related issues
October 15, 2022 - UPDATE: Figured it out. Had to change the relationship to one-to-many on the Image model, then the following queries worked: await prisma.image.update({ where: { id }, data: { home: { delete: true } } }); await prisma.image.delete({ where: { id } })
🌐
GitHub
github.com › prisma › prisma › issues › 5948
deleting a relation via nested delete actually deletes the parent object · Issue #5948 · prisma/prisma
March 2, 2021 - bug/0-unknownBug is new, does not ... relationship called asset via a nested update like so: await prisma.work.update({ where: { id }, data: { asset: { delete: true } }, }); the parent Work resource is actually deleted...
Author   prisma
🌐
Prisma
prisma.io › home › crud › crud › crud › crud
CRUD (Reference) | Prisma Documentation
When working with relational databases, this function doesn't scale as well as having a more generic solution which looks up and TRUNCATEs your tables regardless of their relational constraints. Note that this scaling issue does not apply when using the MongoDB connector. Note: The $transaction performs a cascading delete on each models table so they have to be called in order.