Skip to content
VibORM
Esc
↑↓navigate↵open⌘Jpreview
On this page

Many-to-Many

Define many-to-many relationships connecting multiple records on both sides

A many-to-many relationship is what two s.toMany slots spell. Neither factory name says “many-to-many”: the pair does, and the junction table follows from it.

Basic Example

import { s } from "viborm";

const post = s.model({
  id: s.string().id().ulid(),
  title: s.string(),
  tags: s.toMany(() => tag),
});

const tag = s.model({
  id: s.string().id().ulid(),
  name: s.string().unique(),
  posts: s.toMany(() => post),
});

When these models are registered under the schema keys post and tag, VibORM automatically creates a junction table post_tag with postId and tagId columns.

Characteristics

Aspect Value
Returns Array on both sides
Junction table Auto-created or explicit
Can be empty Yes (empty array)
FK location Junction table

Configuration

The foreign keys live in a junction table, configured with .through(), .source() and .target(). Supplying all three pins the ordinary junction’s table and both side tokens independently of generated names. See the relation method reference and referential actions:

s.toMany(() => tag)
  .name("labels")           // Pairing label, matched exactly on both endpoints
  .through("post_tags")     // Junction table name
  .source("post_id")        // THIS endpoint's column, or compound-key prefix
  .target("tag_id")         // The other endpoint's column, or compound-key prefix
  .onDelete("cascade")      // Referential action for both FKs...
  .onUpdate({ source: "cascade", target: "restrict" }) // ...or one per FK

One junction, one owner. These five methods describe one physical table, so exactly one endpoint declares them; the other endpoint declares none and reads the mirrored view. Configuring both sides is refused with R011. .source() always means the side that spells it, so moving the configuration to the other endpoint swaps .source() and .target() and leaves the table unchanged.

Junction actions accept cascade, restrict and noAction — but not setNull: every junction column carries the membership itself, so nulling one would erase the row’s meaning rather than clear a reference.

Different actions for the two foreign keys

A junction has two foreign keys, and they need not share a policy. Pass { source, target } instead of one action: source is the key to the model that declares the configuration, target the key to its target model. These are the same words .source() and .target() use, not the order of the columns in the table. Declared on post.topics, .onDelete({ source: "cascade", target: "noAction" }) removes a post’s memberships when the post is deleted, and refuses to delete a topic that is still assigned to a post. A nested delete through a post’s own topics (post.update({ where, data: { topics: { delete: … } } })) first removes that post’s membership, so it deletes a topic assigned to that post alone and is refused, changing nothing, while another post still holds the topic.

The map states both keys; a missing side, an unknown key and setNull on either side are refused where you write them. A bare action is shorthand for the same action on both keys, and { source: "cascade", target: "cascade" } is exactly "cascade". An action you do not state stays cascade on both keys.

The one-owner rule still holds, so the other endpoint cannot declare “its” side. To move the configuration there, swap the two sides as you swap .source() and .target(): topic.posts declaring .onDelete({ source: "noAction", target: "cascade" }) is the same table with the same two constraints, and pushing one after the other is a no-op.

.source() and .target() remain scalar configuration methods even when an endpoint uses a compound primary key. A one-field key uses the supplied string as its exact junction column. A compound key expands it as a positional prefix in the primary key’s declared field order:

const post = s.model({
  tenantId: s.string(),
  localId: s.string(),
  tags: s.toMany(() => tag)
    .through("post_tags")
    .source("post")
    .target("tagId"),
}).id(["tenantId", "localId"]);

// Junction columns: post_1, post_2, tagId
// post_1 -> post.tenantId; post_2 -> post.localId

The suffix is positional by design. Renaming or mapping a primary-key field does not turn its field name into junction storage; the declared primary-key order remains the source of truth.

Auto-Generated Junction Table

Without explicit configuration, VibORM generates:

// For: post.tags = s.toMany(() => tag) paired with tag.posts = s.toMany(() => post)
// Junction table: post_tag
// Columns: postId, tagId

The generated table and non-self side tokens are derived from the models’ schema object keys, lowercased, with the table keys sorted alphabetically: post + tag → post_tag. JavaScript variable names and .map() table names do not participate. Renaming a schema key therefore renames generated junction storage; use the complete .through().source().target() configuration when the physical names must stay fixed.

When the pair carries a .name(), the generated table name gains it as a suffix, so several relationships between the same two models never collide.

Explicit Junction Table

Put every override on one endpoint. The other side is left bare:

const post = s.model({
  id: s.string().id().ulid(),
  title: s.string(),
  tags: s.toMany(() => tag)
    .through("post_tags")
    .source("post_id")
    .target("tag_id"),
});

const tag = s.model({
  id: s.string().id().ulid(),
  name: s.string().unique(),
  posts: s.toMany(() => post),   // mirrors the configuration above
});

tag.posts reads the same table with the sides swapped — tag_id is its source and post_id its target — without repeating a single fact.

Querying Many-to-Many

// Include tags when fetching post
const post = await client.post.findUnique({
  where: { id: "post_123" },
  include: { tags: true },
});
// post.tags: Tag[]

// Connect and disconnect tags
await client.post.update({
  where: { id: "post_123" },
  data: {
    tags: {
      connect: [{ id: "tag_1" }],
      disconnect: [{ id: "tag_2" }],
    }
  }
});

See To-Many Relation Filters for some/every/none and Nested Writes for connect/disconnect/set/connectOrCreate.

Common Patterns

Explicit Junction Model

When you need additional data on the relation, you can model the junction table yourself with two singular relations, which then has no many-to-many of its own. To keep the many-to-many and its link row both, see A model as the junction.

// Junction model with extra fields
const enrollment = s.model({
  id: s.string().id().ulid(),
  studentId: s.string(),
  courseId: s.string(),
  enrolledAt: s.dateTime().now(),
  grade: s.string().nullable(),
  student: s.toOne(() => student)
    .fields("studentId")
    .references("id"),
  course: s.toOne(() => course)
    .fields("courseId")
    .references("id"),
})
  .map("enrollments")
  .unique(["studentId", "courseId"]);

const student = s.model({
  id: s.string().id().ulid(),
  name: s.string(),
  enrollments: s.toMany(() => enrollment),
});

const course = s.model({
  id: s.string().id().ulid(),
  title: s.string(),
  enrollments: s.toMany(() => enrollment),
});

Self-Referential Many-to-Many

Two collection slots on the same model pair with each other, and their side tokens default to the field names — no configuration required:

const user = s.model({
  id: s.string().id().ulid(),
  name: s.string(),
  following: s.toMany(() => user),   // junction column: followingId
  followers: s.toMany(() => user),   // junction column: followersId
});

Name the columns yourself by putting every override on one of the two slots:

const user = s.model({
  id: s.string().id().ulid(),
  name: s.string(),
  following: s.toMany(() => user)
    .through("user_follows")
    .source("follower_id")
    .target("following_id"),
  followers: s.toMany(() => user),
});

A model as the junction

When the link itself has columns (who added it, when, in which role) or a tenant, declare it as a model and name it with .through(() => model). The model keeps its delegate, its own table, columns, indexes and constraints; VibORM generates no junction table for it. Reads, filters, recurse and counts on the relation work as on any many-to-many.

const teamParent = s.model({
    organizationId: s.string(),
    childId: s.string(),
    parentId: s.string(),
    createdAt: s.dateTime().now(),
    role: s.string().default("member"),
    child: s
      .toOne(() => team)
      .fields("organizationId", "childId")
      .references("organizationId", "id")
      .onDelete("cascade"),
    parent: s
      .toOne(() => team)
      .fields("organizationId", "parentId")
      .references("organizationId", "id")
      .onDelete("cascade"),
  })
  .id(["childId", "parentId"]);

const team = s.model({
    id: s.string().id(),
    organizationId: s.string(),
    parents: s
      .toMany(() => team)
      .name("teamGraph")
      .through(() => teamParent)
      .source("child")
      .target("parent"),
    children: s.toMany(() => team).name("teamGraph"),
  })
  .unique(["organizationId", "id"]);

.source() and .target() name the model’s to-one relations: source is the one pointing at the row that declares .through(). They may be left out when one to-one aims at each side; a self relation has two and must state them.

Those two to-ones need no inverse on team, unlike every other relation of a schema: the collection that hops through them is their other end. Declare one if you want the link rows as a relation (parentLinks: s.toMany(() => teamParent), with the same .name() on both), and it pairs as usual. Without an inverse, teamParent.child reads as Team | null in types, because the proof a to-one cannot be empty goes through its partner. The row is always there.

Refused when the schema is checked Code
A model the schema does not register, or a getter that throws JT004
A side that is missing, not a to-one with .fields().references(), nullable, aimed at the wrong model, or both sides naming one relation JT005
A side it cannot choose: a self relation stating none, or several candidates JT006
A junction model storing a polymorphic relation JT007
No .id() or .unique() over the pair (see below) JT008
One model as the junction of two pairs JT009
.onDelete() / .onUpdate() beside the model: they belong on its to-ones JT010

The key. A repeated connect must stay idempotent, so a key must lie inside the two sides’ columns and hold every column one side alone contributes. It may leave out a column the sides share (organizationId above) only where that column follows from a side’s other fields, as it does here because team.id is unique: otherwise the same pair under two organizations would be one link.

Referential actions are the to-ones’ own, so an undeclared onDelete is restrict here, not the cascade of a generated junction.

Moving a generated junction to a model of the same table keeps the table and its rows: push adds the new columns and changes the constraints. A NOT NULL column with no default on a populated table is refused as any such column is.

include: { parents: true } returns the target rows and nothing else. Ask for the link row in the relation’s nested select or include:

await db.team.findMany({
  select: {
    id: true,
    parents: {
      where: { name: "core" },
      orderBy: { name: "asc" },
      take: 10,
      select: { id: true, $through: { select: { createdAt: true } } },
    },
  },
});
// [{ id, parents: [{ id, $through: { createdAt } }] }]

$through: true is every scalar of the model; { select } names some. The value is the link that produced that target, whichever parent reached it. It takes scalars only.

await db.team.findMany({
  where: {
    parents: { some: { name: "core", $through: { role: "owner" } } },
  },
});

$through sits beside the target’s own conditions in some, none, every and a relation’s nested where, and both hold on one link and its target: a team with an owner link to one parent and a parent named core through another does not match. It takes a filter over the model’s scalars, at the top level of the body, not inside its AND / OR / NOT.

parents: { connect: { id: "t1", $through: { role: "owner" } } }
parents: { create: { name: "x", $through: { role: "owner" } } }
parents: { connectOrCreate: { where: { id }, create: { name }, $through: { role: "owner" } } }
parents: { set: [{ id: "t1", $through: { role: "owner" } }] }

$through states the model’s own scalars, through the model’s own validation; the columns the two sides fill (organizationId, childId, parentId) and relations are refused. Every other column takes its default or generator. A required column with no default is legal: $through is then required on those verbs, in types and at runtime, and upsert and createMany on that relation are refused.

A link that already exists takes the columns you stated and keeps the others, and a connect with no $through leaves it alone. set keeps the links it retains, so their other columns survive. PostgreSQL, SQLite and D1 do this in one statement (ON CONFLICT (key) DO UPDATE), MySQL in two (the insert, then an UPDATE).

Two rows in different organizations share no link: when both sides supply a column (organizationId), rows that disagree are refused before any statement.

Extensions

A hop is storage. Rules, soft delete, write hooks and default data on the junction model apply to direct calls on its delegate, not to a plain connect or to the walk from team to its parents. Applying softDelete to a junction model is refused when it is applied, because a tombstoned link would still be followed.

$through is a read or a write of that model, so what a direct call would hide or judge is never passed by:

On the junction model $through read or filter $through write
A rule or a permissions rule that can leave a row out refused refused
A rule that hides nothing (read: true) admitted refused if it judges writes
A read-gated field refused where named n/a
A defaults value or an on write hook n/a refused; hooks do not fire on links
defaultOmit honoured on $through: true; a stated select stands n/a

With permissions({ tenant }), a junction model holding the tenant’s field is bound like any other: a walk in a positive test reads its tenant’s links. A none or every is not narrowed.

Was this page helpful?