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
Discussions

how to create or update many-to-many relation?
i tried to insert or update user <-> artist relation with this query but i'm getting Bad Request error: await prisma.user.upsert({ where: { email: user.email }, create: { name: user.name, email: user.email, followings: { connectOrCreate: followings } }, update: { followings: { connectOrCreate: ... More on github.com
🌐 github.com
2
1
mysql - Create or update one to many relationship in Prisma - Stack Overflow
I'm trying to update a one to many relationship in Prisma. My schema looks like this model A_User { id Int @id username String age Int bio Strin... More on stackoverflow.com
🌐 stackoverflow.com
How to connect to more than one relation using Prisma Client upsert function? - Stack Overflow
This is how my prisma upsert function is currently defined: More on stackoverflow.com
🌐 stackoverflow.com
Upserting a document and nesting an upsert of a one-to-many relation using a key that is created when the parent document is created?
For the upsert query, a record needs to be uniquely identified in order to decide whether a record needs to be inserted or updated. In this case, as the uniqueness is dependent on both the userId and mode Prisma client prompts you to pass both the userId and mode. More on github.com
🌐 github.com
2
1
November 17, 2022
🌐
Prisma
prisma.io › home › relation queries › relation queries › relation queries › relation queries
Relation queries (Concepts) | Prisma Documentation
const result = await prisma.post.update({ where: { id: 6, }, data: { author: { upsert: { create: { email: "bob@prisma.io", name: "Bob the New User", }, update: { email: "bob@prisma.io", name: "Bob the existing user", }, }, }, }, include: { author: true, }, }); You can nest create or createMany inside an update to add new related records to an existing record.
🌐
Prisma
prisma.io › home › crud › crud › crud › crud
CRUD (Reference) | Prisma Documentation
To emulate findOrCreate(), use upsert() with an empty update parameter. await prisma.post.updateMany({ data: { views: { increment: 1 }, likes: { increment: 1 }, }, }); See Relation queries for connecting and disconnecting related records.
🌐
Paigeniedringhaus
paigeniedringhaus.com › blog › tips-and-tricks-for-using-the-prisma-orm
Tips and Tricks for Using the Prisma ORM | Paige Niedringhaus
Unfortunately there’s currently no single related record upsert() function that will both delete previously related records and create newly related records, but maybe one day Prisma will include this use case.
Top answer
1 of 2
14

I'm providing my solution based on the clarifications you provided in the comments. First I would make the following changes to your Schema.

Changing the schema

model A_User {
  id        Int          @id
  username  String
  age       Int
  bio       String       @db.VarChar(1000)
  createdOn DateTime     @default(now())
  features  A_Features[]
}

model A_Features {
  id          Int      @id @default(autoincrement())
  description String   @unique
  users       A_User[]
}

Notably, the relationship between A_User and A_Features is now many-to-many. So a single A_Features record can be connected to many A_User records (as well as the opposite).

Additionally, A_Features.description is now unique, so it's possible to uniquely search for a certain feature using just it's description.

You can read the Prisma Guide on Relations to learn more about many-to-many relations.

Writing the update query

Again, based on the clarification you provided in the comments, the update operation will do the following:

  • Overwrite existing features in a A_User record. So any previous features will be disconnected and replaced with the newly provided ones. Note that the previous features will not be deleted from A_Features table, but they will simply be disconnected from the A_User.features relation.

  • Create the newly provided features that do not yet exist in the A_Features table, and Connect the provided features that already exist in the A_Features table.

You can perform this operation using two separate update queries. The first update will Disconnect all previously connected features for the provided A_User. The second query will Connect or Create the newly provided features in the A_Features table. Finally, you can use the transactions API to ensure that both operations happen in order and together. The transactions API will ensure that if there is an error in any one of the two updates, then both will fail and be rolled back by the database.


//inside async function
const disconnectPreviouslyConnectedFeatures =  prisma.a_User.update({
    where: {id: 1},
    data: {
        features: {
            set: []  // disconnecting all previous features
        }
    }
})

const connectOrCreateNewFeatures =  prisma.a_User.update({
    where: {id: 1},
    data: {
        features: {
            // connect or create the new features
            connectOrCreate: [
                {
                    where: {
                        description: "'first feature'"
                    }, create: {
                        description: "'first feature'"
                    }
                },
                {
                    where: {
                        description: "second feature"
                    }, create: {
                        description: "second feature"
                    }
                }
            ]
        }
    }
})

// transaction to ensure either BOTH operations happen or NONE of them happen.
await prisma.$transaction([disconnectPreviouslyConnectedFeatures, connectOrCreateNewFeatures ])

If you want a better idea of how connect, disconnect and connectOrCreate works, read the Nested Writes section of the Prisma Relation queries article in the docs.

2 of 2
2

The TypeScript definitions of prisma.a_User.update can tell you exactly what options it takes. That will tell you why the 'features' does not exist in type error is occurring. I imagine the object you're passing to data takes a different set of options than you are specifying; if you can inspect the TypeScript types, Prisma will tell you exactly what options are available.

If you're trying to add new features, and update specific ones, you would need to specify how Prisma can find an old feature (if it exists) to update that one. Upsert won't work in the way that you're currently using it; you need to provide some kind of identifier to the upsert call in order to figure out if the feature you're adding already exists.

https://www.prisma.io/docs/reference/api-reference/prisma-client-reference/#upsert

You need at least create (what data to pass if the feature does NOT exist), update (what data to pass if the feature DOES exist), and where (how Prisma can find the feature that you want to update or create.)

You also need to call upsert multiple times; one for each feature you're looking to update or create. You can batch the calls together with Promise.all in that case.

const upsertFeature1Promise = prisma.a_User.update({
  data: {
    // upsert call goes here, with "create", "update", and "where"
  }
});
const upsertFeature2Promise = prisma.a_User.update({
  data: {
    // upsert call goes here, with "create", "update", and "where"
  }
});
const [results1, results2] = await Promise.all([
  upsertFeaturePromise1,
  upsertFeaturePromise2
]);
🌐
GitHub
github.com › prisma › prisma › discussions › 22501
Upsert with a nested to-many set · prisma/prisma · Discussion #22501
model TodoList { id Int @id @default(autoincrement()) title String authorId Int items TodoItem[] @unique([authorId, title]) } model TodoItem { id Int @id @default(autoincrement()) name String listId String list TodoList @relation(fields: [listId], references: [title]) @unique([listId, name]) } You can imagine wanting to build an API where a client wants to save a list with items. If the list already exists, it's overwritten. Is it possible to do this in prisma with one query? prisma.todoList.upsert({ where: { authorId_title: { title: args.title, authorId: args.authorId } }, create: { title: args.title, items: { createMany: { data: args.items.map((item) => { return { name: item.name } }) } } }, update: { items: { set: args.items.map((item) => { return { listId_name: { listId: ** I don't know the list Id**, name: item.name }, name: item.name } }) } } }
Author   prisma
Find elsewhere
🌐
GitHub
github.com › prisma › prisma › issues › 12240
connectOrCreate on 1-1 relation always triggers create on upsert · Issue #12240 · prisma/prisma
March 10, 2022 - Imagine a Prisma schema where you have a User model and an Author model which have a 1-1 relation. In an application I have created a User (id: A) with a related Author record (id: B). When using prisma.user.upsert on User A with a related Author B record I use author.connectOrCreate in the update clause of the prisma.user.upsert operation.
Author   prisma
🌐
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, }, });
🌐
Goprisma
goprisma.org › docs › walkthrough › upsert
Upsert records – Prisma Client Go
October 22, 2024 - Use upsert to update or create records depending on whether it already exists or not.
🌐
Reddit
reddit.com › r/reactjs › prisma orm relation updates
r/reactjs on Reddit: Prisma ORM Relation Updates
August 20, 2022 -

Hello all, I am creating a web app in NextJS and I'm using the Prisma ORM. I have a user table that has a foreign key to a status table in a one to many relationship. I am implementing the functionality to update the status on a user account but I'm having difficulties. The following is the code snippet I'm using:

  const user = await db.user.update({
    where: {
      id,
    },
    data: {
      status: {
        connect: {
          id: statusId,
        },
      },
    },
  });

I get the following error:

error - PrismaClientValidationError: 
Invalid `prisma.user.update()` invocation:

{
  where: {
    id: 'cl706mhjt0006kouzjrzd2kf9'
  },
  data: {
    status: {
    ~~~~~~
      connect: {
        id: '3'
      }
    }
  }
}

Unknown arg `status` in data.status for type UserUncheckedUpdateInput. Did you mean `statusId`?

I also get the same error if I try to change the statusId field. I'm probably doing something dumb.. Thanks in advance.

EDIT: This has been solved.

First thing, you don't need to use the connect method to update the relation on the table. While it works, it's easier just to update the statusId directly.

Second, the error was actually due to a type mismatch. The id being passed as it turns out was a string. The way I parsed and sent my forms from the frontend to the backend converted the type into that string. After doing a parseInt on the id it resolved my error and worked correctly.

🌐
YouTube
youtube.com › watch
How to Connect to More Than One Relation Using Prisma Client Upsert Function - YouTube
Learn how to resolve the common error in Prisma Client when trying to connect multiple relations, particularly with the upsert function.---This video is base...
Published   March 27, 2025
Views   2
🌐
xjavascript
xjavascript.com › blog › how-to-upsert-many-fields-in-prisma-orm
How to Upsert Multiple Fields in Prisma ORM with a Single Query: A Complete Guide — xjavascript.com
If your model has relations (e.g., a Product belongs to a Category), Prisma lets you upsert nested records using connectOrCreate.
🌐
DEV Community
dev.to › this-is-learning › its-prisma-time-update-1mmi
It's Prisma Time - Update - DEV Community
January 7, 2022 - In the insert operation, we saw that when we want to insert a new record, we can use create, connect or connectOrCreate operation to create a relation between two records.
🌐
Brendonovich
prisma.brendonovich.dev › writing-data › update
Update Queries - Prisma Client Rust - Brendonovich
December 31, 2023 - IMPORTANT: Updating a relation this way with update_many will cause the query to always return an error. To avoid this, set the relation's scalar fields directly.