skip to content

In Prisma Client 7, how do nested create, connect, connectOrCreate, disconnect and set write across an order's relations in one call?

level: middleimportance: must knowfreq 68%

answer

  1. one call, one transaction
  2. new row versus existing row
  3. a unique filter picks the target
  4. disconnect needs an optional side
  5. set replaces the whole list

basics

~20 s

A nested write lets one create or update call write related records too, in one transaction that rolls back as a whole: create adds rows, connect links existing ones by a unique filter, connectOrCreate does either, disconnect unlinks and set replaces a list.

solid answer

~50 s

Inside the `data` of a `create` or `update`, each relation field accepts nested operations, and Prisma Client runs the whole call as **one transaction**: if the third order line fails, the order and the first two lines are rolled back too. `create` inserts new related rows. `connect` links existing ones through a **unique** filter (`{ id }`, `{ sku }`), and a missing target makes the whole write fail. `connectOrCreate` takes a unique `where` plus `create` data and does whichever applies. `disconnect` removes a link without deleting either record, and works only where the relation is optional (`disconnect: true` on a to-one). `set` replaces a to-many list, dropping every link not named. Two type-level rules catch people out. A data object uses either the relation field (`user: { connect: ... }`) or the scalar (`userId`), never both. Nested `createMany` exists only on one-to-many relations and cannot nest further.

code

ts · 11 lines
ts
await prisma.order.update({
  where: { id: 42 },
  data: {
    tags: { disconnect: [{ name: "gift" }] },
  },
});

await prisma.user.update({
  where: { id: 7 },
  data: { referredBy: { disconnect: true } },
});

go deeper

for a junior

Recall the difference between nested create and connect, and that connect needs an id or other unique field.

for a middle

Explain that a nested write is one transaction, how disconnect and set differ, and why data cannot mix userId with user: { connect }.

for a senior

Show the edge cases you have hit: set clearing links, disconnect failing on a required relation, nested createMany refused on a many-to-many, a missing connect target failing the call.

for a principal

Set a team convention for writes, checked relation inputs over raw foreign-key scalars, so missing targets fail with clear errors.

## What a nested write is A **nested write** is a Prisma Client `create` or `update` whose `data` also writes through **relation fields**. Instead of inserting an order, reading its id and then inserting its lines, you describe the whole graph in one object. Prisma Client then runs the statements it needs inside **a single transaction**. If any part fails, for example the third order line violates a constraint, every change from that call is rolled back. You never see an order with only two of its three lines. Nested operations are available on relation fields in `create`, `update` and `upsert` data. They are **not** available in top-level `createMany` or `createManyAndReturn`, which accept scalar fields only. ## The operations | Operation | Target | Effect | Where it is offered | | --- | --- | --- | --- | | `create` | new rows | inserts them and links them | to-one and to-many | | `createMany` | new rows | bulk insert, optional `skipDuplicates` | one-to-many lists only | | `connect` | existing rows, by unique filter | links them; missing target fails the call | to-one and to-many | | `connectOrCreate` | unique `where` plus `create` | links if found, otherwise creates and links | to-one and to-many | | `disconnect` | linked rows | removes the link, keeps both records | optional sides only | | `set` | list of unique filters | the list becomes exactly these rows | to-many in `update` | Updates add `update`, `updateMany`, `upsert`, `delete` and `deleteMany` for changing or removing related rows themselves. ## A checkout in one call With an explicit `OrderItem` join model and an implicit `Order`-`Tag` relation, one call can link a known user, add lines for existing products and tag the order: ```ts const order = await prisma.order.create({ data: { user: { connect: { email: "[email protected]" } }, items: { create: [ { quantity: 2, product: { connect: { sku: "MUG-01" } } }, { quantity: 1, product: { connect: { sku: "TEE-M" } } }, ], }, tags: { connectOrCreate: [{ where: { name: "gift" }, create: { name: "gift" } }], }, }, }); ``` Every filter inside `connect` and `connectOrCreate.where` is a **unique input**: an `@id`, an `@unique` field or a compound unique. A plain filter such as `{ status: "ACTIVE" }` does not type-check there. If `MUG-01` does not exist, Prisma Client throws a `PrismaClientKnownRequestError` saying the required records were not found, and the order is not created. ## Rules that trip people up - **Checked versus unchecked input.** `data` is typed as an exclusive choice between `OrderCreateInput`, which uses `user: { connect: ... }`, and `OrderUncheckedCreateInput`, which sets `userId: 1` directly. Writing both in one object fails type-checking. The checked form is the one the docs recommend, and it gives a clearer error when the target is missing. - **`disconnect` needs an optional relation.** On a to-one side you write `referredBy: { disconnect: true }`; on a list you name the rows, `tags: { disconnect: [{ name: "gift" }] }`. On a many-to-many this deletes join rows only; the tags themselves stay. - **`set` is a replacement, not an addition.** `tags: { set: [{ id: 3 }] }` leaves the order linked to tag 3 alone. On a one-to-many, the rows `set` drops lose their foreign key, so their side must be optional. When `set` and `connect` appear together, the order matters: `set` clears the list, so a `connect` that runs before it is undone. - **Nested `createMany` is narrow.** It works for a one-to-many list (an order's `items`) but not for a many-to-many such as `tags`, and you cannot nest another `create` or `createMany` inside it. Choose it over nested `create` mainly when you need `skipDuplicates`. - **Explicit join models add a level.** Linking a product through `OrderItem` is `items: { create: [{ quantity, product: { connect } }] }`, not `products: { connect }`. ## What nested writes do not cover A nested write is atomic only for the one call that contains it. Several separate calls that must succeed together need `prisma.$transaction`, which is a separate subject. Returning the related rows with `include` or `select` belongs to Prisma Client's query API. And `connectOrCreate` is not race-free under concurrency: two calls can both miss and both try to create, so the loser gets a unique-constraint error. Read correctly, the nested-write API is a compact description of the target state of one aggregate: what to create, what to link, what to unlink. Prisma turns it into the statements and wraps them in one transaction.

  • When would you pick nested createMany over nested create?
    Mostly when you need `skipDuplicates`, which nested `create` lacks. Nested `createMany` is limited: it works only on a one-to-many list such as an order's `items`, not on a many-to-many, and it cannot contain another `create` or `createMany`. For anything deeper, nested `create` is the tool, and the Prisma docs suggest it as the default.
  • What does set do when combined with connect in the same update?
    `set` replaces the whole list, so ordering decides the result. If `set` is applied first, the following `connect` adds to the fresh list. If `connect` runs first, `set` then clears everything and leaves only its own rows, undoing the `connect`. Prefer one or the other in a single update so the result does not depend on that ordering.
  • Why might disconnect on User.profile type-check but still fail at runtime?
    The generated update type for the back side of a one-to-one can offer `disconnect`, but if `Profile.userId` is required the link lives in a non-nullable column. Disconnecting would leave a profile without a user, so Prisma rejects the write as a violation of the required relation. Make the relation optional, or delete the profile instead.

  • Each nested operation commits separately, so a failure leaves the parent row behind.
  • connect accepts any filter, such as a non-unique status field.
  • set adds the named records and keeps the existing links.
  • disconnect deletes the related record from its table.
  • Nested createMany can create the tags of a many-to-many relation.
  • Passing userId and user: { connect } together is the safest, most explicit form.