Skip to content

Relations, Eager Loading & Pivot Tables ​

Connect related models using explicit relation methods (hasOne, hasMany, belongsTo, belongsToMany). Relations load in batched WHERE IN queries when requested via .with(...) or instance.load(...), so you never run into accidental N+1 queries and instance.relations is always statically typed to the exact relations you loaded.


1. Defining Relations ​

MethodReturn TypeRelationship
this.hasOne(() => Target, { foreignKey, localKey })HasOne<Target, FK>1-to-1 where Target holds the foreign key
this.hasMany(() => Target, { foreignKey, localKey })HasMany<Target, FK>1-to-many where Target holds the foreign key
this.belongsTo(() => Target, { foreignKey, ownerKey })BelongsTo<Target>Inverse 1-to-1 / many-to-1 where this holds foreignKey
this.belongsToMany(() => Target, { pivotTable, foreignPivotKey, relatedPivotKey, localKey?, relatedKey?, pivotColumns? })BelongsToMany<Target, Pivot>Many-to-many through an explicit pivot table
typescript
export class User extends Model.define({
  table: "users",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    name: col.text().notNull(),
  },
}) {
  public profile(): HasOne<Profile, "userId"> {
    return this.hasOne(() => Profile, { foreignKey: "userId", localKey: "id" });
  }

  public posts(): HasMany<Post, "authorId"> {
    return this.hasMany(() => Post, { foreignKey: "authorId", localKey: "id" });
  }

  public roles(): BelongsToMany<Role, { assignedAt: Date; grantedBy: string }> {
    return this.belongsToMany(() => Role, {
      pivotTable: "role_user",
      foreignPivotKey: "user_id",
      relatedPivotKey: "role_id",
      pivotColumns: {
        assignedAt: col.timestamp().column("assigned_at").default(() => new Date()),
        grantedBy: col.text().column("granted_by").default("system"),
      },
    });
  }
}

2. Direct Relation Queries & Mutations ​

Relation methods return a typed relation handle bound to the parent instance:

HasOne & HasMany ​

typescript
// Query related children (accepts `.where()`, `.orderBy()`, `.limit()`, `.offset()`)
const profile = await user.profile().get(); // Profile | null
const publishedPosts = await user
  .posts()
  .where("published", "=", true)
  .orderBy("createdAt", "desc")
  .get();

const postCount = await user.posts().count();
const hasPosts = await user.posts().exists();

// Create child with foreignKey pre-filled automatically:
const newPost = await user.posts().create({
  title: "Typed Relations",
  published: true,
});

// Create multiple children in a batch:
await user.posts().createMany([
  { title: "Part 1", published: true },
  { title: "Part 2", published: false },
]);

// Save an existing or unsaved child onto the parent (sets foreignKey & saves):
const draft = orm.posts.make({ authorId: user.id, title: "Attached Draft" });
await user.posts().save(draft);

// Delete all matching children (respects softDeletes & model delete hooks):
await user.posts().delete();

// Strict repository helper when you want full cross-model validation:
const viaRepo = await orm.users.relation(user, "posts").create({ title: "Strict" });

BelongsTo (associate & dissociate) ​

typescript
const post = await orm.posts.findOrFail(postId);
const author = await post.author().get(); // User | null

// Re-assign foreign key in memory (call `.save()` to persist):
const bob = await orm.users.findOrFail(bobId);
post.author().associate(bob);
await post.save();

// Clear a nullable foreign key (`dissociate()`):
post.author().dissociate();
await post.save();

3. Many-to-Many (BelongsToMany) & Pivot Columns ​

Pivot tables declared in belongsToMany are automatically created and indexed by orm.syncSchema(). Pivot attributes are decoded with their column codecs and exposed on related.pivot:

typescript
const user = await orm.users.findOrFail(userId);
const adminRole = await orm.roles.where("name", "=", "admin").firstOrFail();
const editorRole = await orm.roles.where("name", "=", "editor").firstOrFail();

// Attach by ID array or object/Map with pivot attributes:
await user.roles().attach([adminRole.id]);
await user.roles().attach({
  [editorRole.id]: { grantedBy: "[email protected]" },
});

// When related keys are `bigint` (`col.int64()`), pass a `Map` to preserve key types:
const bigintMap = new Map<bigint, { grantedBy?: string }>([
  [10n, { grantedBy: "root" }],
]);
await user.roles().attach(bigintMap);

// Read related models with strongly typed `.pivot`:
const roles = await user.roles().get();
roles[0].pivot.assignedAt; // Date
roles[0].pivot.grantedBy;  // string

// Update pivot columns on an existing link:
await user.roles().updateExistingPivot(editorRole.id, { grantedBy: "admin" });

// Sync (attaches missing, updates provided pivot attrs, detaches omitted IDs):
const syncResult = await user.roles().sync({
  [adminRole.id]: { grantedBy: "sync-job" },
});
// syncResult => { attached: [...], detached: [...], updated: [...] }

// Additive sync without detaching existing links:
await user.roles().sync([editorRole.id], { detaching: false });

// Toggle membership:
const toggled = await user.roles().toggle([adminRole.id, editorRole.id]);
// toggled => { attached: [...], detached: [...] }

// Detach specific IDs, or call `.detach()` with no args to clear all links:
await user.roles().detach([editorRole.id]);

4. Batched Eager Loading (.with() & .load()) ​

.with(...) executes one batched WHERE IN query per relation (automatically chunked into batches of 5,000 keys—no N+1 queries) and statically types model.relations:

typescript
const users = await orm.users
  .query()
  .with({
    profile: true,
    roles: {
      orderBy: { column: "name", direction: "asc" },
    },
    posts: {
      where: (q) => q.where("published", "=", true),
      orderBy: { column: "createdAt", direction: "desc" },
      limit: 5,
      offset: 0,
      withTrashed: false,
      // Nested eager loading + nested counts:
      with: { author: true },
    },
  })
  .get();

// Fully typed & narrowed to ONLY the loaded relations:
users[0].relations.profile?.bio;
users[0].relations.posts[0].relations.author?.name;
users[0].relations.roles[0].pivot.assignedAt;

Calling .with() multiple times deep-merges the load specifications cleanly.

Loading Relations on Existing Instances (instance.load()) ​

typescript
const user = await orm.users.findOrFail(userId);
await user.load({
  profile: true,
  posts: { where: (q) => q.where("published", "=", true) },
});

5. Relation Counts (.withCount()) & Existence Filters (.whereHas()) ​

.withCount() ​

Attach relation counts without loading every related record into memory:

typescript
const authors = await orm.users
  .query()
  .withCount({
    posts: true,
    roles: { where: (q) => q.where("name", "=", "admin") },
  })
  .get();

console.log(authors[0].counts.posts); // number
console.log(authors[0].counts.roles); // number

.whereHas(), .whereDoesntHave(), .orWhereHas(), .orWhereDoesntHave() ​

Filter parent models by existence or non-existence of related records (including nested whereHas inside callbacks):

typescript
// Users who have at least one published post, and no "banned" role
const activeWriters = await orm.users
  .query()
  .whereHas("posts", (q) => q.where("published", "=", true))
  .whereDoesntHave("roles", (q) => q.where("name", "=", "banned"))
  .get();

// Nested relation existence & OR combinations
const featured = await orm.users
  .query()
  .whereHas("roles", (q) => q.where("name", "=", "admin"))
  .orWhereHas("posts", (q) => q.where("published", "=", true))
  .get();

Next Steps ​

Released under the MIT License.