For the model, it can be simplified as follows as Prisma supports @updatedAt which will automatically update the column:

model Post {
  author      String     @id
  lastUpdated DateTime   @updatedAt
  categories  Category[]
}

model Category {
  id    Int    @id
  posts Post[]
}

As for the query, it would look like this:

const categories = [
  { create: { id: 1 }, where: { id: 1 } },
  { create: { id: 2 }, where: { id: 2 } },
]
await db.post.upsert({
  where: { author: 'author' },
  create: {
    author: 'author',
    categories: {
      connectOrCreate: categories,
    },
  },
  update: {
    categories: { connectOrCreate: categories },
  },
})

connectOrCreate will create if not present and add the categories to the posts as well.

Answer from Ryan on Stack Overflow
🌐
DEV Community
dev.to › frenkix › prisma-orm-update-explicit-many-to-many-relations-1o6f
Prisma ORM update explicit many to many relations - DEV Community
December 27, 2021 - So, when you have explicit many to many relationship, lets say you have post that has multiple tags. And you want to edit that post and pass up new tags or edit/remove existing ones. This is the way to do it: const response: jobs = await prisma.posts.update({ data: { ...data, users: { connect: { id: session.user.id } }, posts_tags: { deleteMany: {}, create: tags.map((tag) => ({ tags: { connect: { id: tag } }, })), }, }, where: { slug: postSlug, }, }); So first you pass up deleteMany: {}, which will delete all connections between post and tags.
Discussions

How to update many-to-many relationship in prisma?
I wanted to make a chat application that can do: user's can send/receive friend requests when user1 send friend request to user2 and if the user2 accepts the request : the user2 and user1's frie... More on stackoverflow.com
🌐 stackoverflow.com
Explicit many-to-many relationship updating the relation table is not working
Bug description Unable to update the relation table as implicit many to many relations. How to reproduce Below is the prisma schema: model user { id String @id @default(uuid()) email String @unique... More on github.com
🌐 github.com
2
2
How to update a many to many relationship?
If this discussion still requires ... one with updated details. Your contributions are invaluable to the community, and we’re here to help! For more details about our priorities and vision for the future of Prisma ORM, check out our latest blog post: https://www.prisma.io/blog/prisma-orm-manifesto... More on github.com
🌐 github.com
2
1
How to update a many to many relationship in Prisma? - Stack Overflow
I am modelling a boxing tournament. Boxers and Fights have a many-to-many relationship: A Boxer has many Fights A Fight has many Boxers (exactly 2) Here are the models in the schema model Fight {... More on stackoverflow.com
🌐 stackoverflow.com
December 29, 2021
🌐
Stack Overflow
stackoverflow.com › questions › 77773925 › how-to-update-many-to-many-relationship-in-prisma
How to update many-to-many relationship in prisma?
@relation("ReceivedFriendRequests", fields: [receiverId], references: [id]) receiverId String? status FriendRequestStatus @default(PENDING)// Define FriendRequestStatus enum & set to pending by default @@unique([senderId, receiverId]) } enum FriendRequestStatus { PENDING ACCEPTED DECLINED } export async function POST(req: NextRequest) { try { const data = await req.json(); // Should preform auth check const { receiverId, requesterId, status } = FriendRequest.parse(data); // Update the friend request status, works for accept & reject await prisma.friend.update({ where: { receiverId, requesterId }, data: { status }, }); return NextResponse.json({ message: `Friend request ${status === "ACCEPTED" ?
Top answer
1 of 1
2

Hi @gurjotkaur20 👋

Thank you for raising this question.

In the context of explicit many-to-many relationships, Prisma does not directly support the set operation as it does with implicit relationships. This is because, with explicit relationships, you are directly managing the join table (users_groups in your case), and Prisma expects you to handle the creation and deletion of records in this table yourself.
However, a workaround to achieve the behavior you're looking for—replacing existing relations with new ones—can be done in two steps:

  • Delete the existing relations from the join table.
  • Create new relations in the join table.

After clearing the existing relations, you then create new ones by updating the groupp model with a create operation under the users field. This operation adds new entries to the users_groups table, linking the groupp to new user(s).

// Step 1: Delete existing relations for the group
await prisma.users_groups.deleteMany({
  where: {
    groupId: 'b81f8b10-9bf6-4589-b95b-fe55430a47f5',
  },
});

// Step 2: Update the group and create or connect new user relations
await prisma.groupp.update({
  where: {
    id: 'b81f8b10-9bf6-4589-b95b-fe55430a47f5',
  },
  data: {
    users: {
      create: [
        { user: { connect: { id: 'newUserId1' } } },
        // Add more users as needed
      ],
    },
  },
});

This approach requires two separate operations and might not be as efficient or atomic as a single set operation in implicit many-to-many relations.

If this answers your question, it would be great if you could mark this Discussion as answered to indicate that it has been resolved.

Otherwise please let us know how else we can help you further or close the Discussion if it was resolved in some other way 🙏

🌐
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 - The set operation replaces all the records in a many-to-many relationship. It will remove any previous relations and set new ones. // Set tags for a post, replacing any existing tags await this.prisma.post.update({ where: { id: 1 }, data: { tags: { set: [{ id: 1 }, { id: 2 }] // Replace existing tags with tag IDs 1 and 2 } } });
Find elsewhere
🌐
GitHub
github.com › prisma › prisma › discussions › 21039
How do I update an implicit many-to-many relationship via a one-to-many? · prisma/prisma · Discussion #21039
To query a count of Person that has a Result connected to a particular Event, you can use the _count parameter with a nested select in Prisma. For example: const eventUuid = 'your-event-uuid'; // replace with your event UUID const personCount = await prisma.person.findMany({ where: { results: { some: { event: { uuid: eventUuid } } } }, select: { uuid: true, firstName: true, _count: { select: { results: true }, }, }, });
Author   prisma
🌐
GitHub
github.com › prisma › prisma › discussions › 11490
How to update Many to Many Relationship · prisma/prisma · Discussion #11490
January 29, 2022 - Schema : model Tag { id Int @id @default(autoincrement()) name String color String slug String @unique posts PostTags[] created_at DateTime @default(now()) updated_at DateTime @updatedAt @@map("tag...
Author   prisma
🌐
Paigeniedringhaus
paigeniedringhaus.com › blog › tips-and-tricks-for-using-the-prisma-orm
Tips and Tricks for Using the Prisma ORM | Paige Niedringhaus
Just like updating related tables can be done in a single transaction with Prisma, querying multiple tables for related data can also be done in a single action. Taking the web app we’ve been talking about, for display purposes in the UI, it’s necessary to have both the individual device ID and the fleet IDs that each device belongs to.
🌐
Prisma
prisma.io › home › many-to-many relations › many-to-many relations › many-to-many relations › many-to-many relations
Modeling and querying many-to-many relations | Prisma Documentation
await prisma.post.update({ where: { id: 1 }, data: { title: "Prisma is awesome!", tags: { set: [{ id: 1 }, { id: 2 }], create: { name: "typescript" } }, }, }); Explicit relations are needed when you need to store extra fields in the relation table or when introspecting an existing database:
🌐
Brendonovich
prisma.brendonovich.dev › writing-data › update
Update Queries - Prisma Client Rust - Brendonovich
December 31, 2023 - use prisma::post; let updated_posts_count: i64 = client .post() .update_many( vec![post::id::contains("id".to_string())], // Vec of filters vec![post::content::set("new content".to_string())] // Updates to be applied to each record ) .exec() .await?;
🌐
Prisma
prisma.io › home › relation queries › relation queries › relation queries › relation queries
Relation queries (Concepts) | Prisma Documentation
Nested readsRelation load strategies ... recordsUpdate all related records (or filter)Update a specific related recordUpdate or create a related recordAdd new related records to an existing recordRelation filtersFilter on "-to-many" relationsFilter on "-to-one" relationsFilter on ...
🌐
Tericcabrel
blog.tericcabrel.com › many-to-many-relationship-prisma
Handle a Many-to-Many relationship with Prisma and Node.js
February 26, 2024 - Replace the content of the file prisma/schema.prisma with the code below to set the provider to MySQL: // This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema generator client { provider = "prisma-client-js" } datasource db { provider = "mysql" url = env("DATABASE_URL") } Open the .env file and update the database URL to the connection string of the MySQL database instance running in Docker.