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

Associations

Connect Models with belongsTo, hasMany, and hasOne.

At a glance

To Write
point at the record a foreign key names author = belongsTo(Author)
reach the records that point at this one articles = hasMany(Article)
reach the one record that points at this one profile = hasOne(Profile)
point at a record of one of several Models likeable = belongsTo([Photo, Video]), hasMany(Like, { as: "likeable" })
narrow or order an association hasMany(Article, { scope: (q) => q.where({ … }) })
remove records with their owner hasMany(Article, { dependent: "destroy" })

Each part of associations has a page of its own:

To See
load an association for many records at once Preloading
save records with their owner Autosaving
reach records through another association Through associations
keep a count of a record’s associated records Counter caches
set updatedAt when an associated record changes Touching
filter by associated records Joins

The Models

The examples use these Models, whose attributes come from their tables through the schema active-record schema generates:

import { hasMany, hasOne } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";
import { Profile } from "./profile";

export class Author extends ApplicationRecord {
  articles = hasMany(Article, { dependent: "destroy" }); // Article's authorId
  profile = hasOne(Profile, { dependent: "delete" }); // Profile's authorId

  // A scope turns finding the inverse off, so name it:
  publishedArticles = hasMany(Article, {
    scope: (q) => q.where({ published: true }),
    inverseOf: "author",
  });
}
import { belongsTo, hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Author } from "./author";
import { Comment } from "./comment";

export class Article extends ApplicationRecord {
  author = belongsTo(Author); // its own authorId
  comments = hasMany(Comment, { dependent: "deleteAll" }); // Comment's articleId
}
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Author } from "./author";

export class Profile extends ApplicationRecord {
  author = belongsTo(Author);
}
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";

export class Comment extends ApplicationRecord {
  article = belongsTo(Article);
}
import { belongsTo, hasMany, type HasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";

export class Category extends ApplicationRecord {
  static top = this.scope((q) => q.where({ parentId: null }));
  static alphabetical = this.scope((q) => q.order({ name: "asc" }));

  parent = belongsTo(Category, { foreignKey: "parentId", optional: true }); // a top category has none

  // Written out: TypeScript can't infer a field whose scope uses its own Model's scopes.
  children: HasMany<typeof Category> = hasMany(Category, {
    foreignKey: "parentId",
    scope: (q) => q.alphabetical(),
  });
}
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Photo } from "./photo";
import { Video } from "./video";

export class Like extends ApplicationRecord {
  likeable = belongsTo([Photo, Video]); // its own likeableType and likeableId
}
import { hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Like } from "./like";

export class Photo extends ApplicationRecord {
  likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Photo"
}
import { hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Like } from "./like";

export class Video extends ApplicationRecord {
  likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Video"
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 936ee2fb777c

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** articles — last changed by 0001_create_tables.sql */
export const articles = {
  id: { type: "string", null: false, generateId: true },
  authorId: { type: "string", null: false },
  title: { type: "string", null: false },
  published: { type: "boolean", null: false, default: () => false },
} as const;

/** authors — last changed by 0001_create_tables.sql */
export const authors = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
} as const;

/** categories — last changed by 0001_create_tables.sql */
export const categories = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  parentId: "string",
} as const;

/** comments — last changed by 0001_create_tables.sql */
export const comments = {
  id: { type: "string", null: false, generateId: true },
  articleId: { type: "string", null: false },
  body: { type: "string", null: false },
} as const;

/** likes — last changed by 0001_create_tables.sql */
export const likes = {
  id: { type: "string", null: false, generateId: true },
  likeableType: { type: "string", null: false },
  likeableId: { type: "string", null: false },
} as const;

/** photos — last changed by 0001_create_tables.sql */
export const photos = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
} as const;

/** profiles — last changed by 0001_create_tables.sql */
export const profiles = {
  id: { type: "string", null: false, generateId: true },
  authorId: { type: "string", null: false },
  bio: "string",
} as const;

/** videos — last changed by 0001_create_tables.sql */
export const videos = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    articles: { attributes: articles, primaryKey: "id" },
    authors: { attributes: authors, primaryKey: "id" },
    categories: { attributes: categories, primaryKey: "id" },
    comments: { attributes: comments, primaryKey: "id" },
    likes: { attributes: likes, primaryKey: "id" },
    photos: { attributes: photos, primaryKey: "id" },
    profiles: { attributes: profiles, primaryKey: "id" },
    videos: { attributes: videos, primaryKey: "id" },
  },
  models: {
    Article: "articles",
    Author: "authors",
    Category: "categories",
    Comment: "comments",
    Like: "likes",
    Photo: "photos",
    Profile: "profiles",
    Video: "videos",
  },
});

declare module "../models/article" {
  interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}

declare module "../models/author" {
  interface Author extends TableAttributes<typeof authors, (typeof Author)["attributes"]> {}
}

declare module "../models/category" {
  interface Category extends TableAttributes<typeof categories, (typeof Category)["attributes"]> {}
}

declare module "../models/comment" {
  interface Comment extends TableAttributes<typeof comments, (typeof Comment)["attributes"]> {}
}

declare module "../models/like" {
  interface Like extends TableAttributes<typeof likes, (typeof Like)["attributes"]> {}
}

declare module "../models/photo" {
  interface Photo extends TableAttributes<typeof photos, (typeof Photo)["attributes"]> {}
}

declare module "../models/profile" {
  interface Profile extends TableAttributes<typeof profiles, (typeof Profile)["attributes"]> {}
}

declare module "../models/video" {
  interface Video extends TableAttributes<typeof videos, (typeof Video)["attributes"]> {}
}
CREATE TABLE authors (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL
);
CREATE TABLE profiles (
  id TEXT PRIMARY KEY NOT NULL,
  author_id TEXT NOT NULL REFERENCES authors (id),
  bio TEXT
);
CREATE TABLE articles (
  id TEXT PRIMARY KEY NOT NULL,
  author_id TEXT NOT NULL REFERENCES authors (id),
  title TEXT NOT NULL,
  published BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE comments (
  id TEXT PRIMARY KEY NOT NULL,
  article_id TEXT NOT NULL REFERENCES articles (id),
  body TEXT NOT NULL
);
CREATE TABLE categories (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  parent_id TEXT REFERENCES categories (id)
);
CREATE TABLE photos (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL
);
CREATE TABLE videos (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL
);
CREATE TABLE likes (
  id TEXT PRIMARY KEY NOT NULL,
  likeable_type TEXT NOT NULL,
  likeable_id TEXT NOT NULL
);
CREATE INDEX index_profiles_on_author_id ON profiles (author_id);
CREATE INDEX index_articles_on_author_id ON articles (author_id);
CREATE INDEX index_comments_on_article_id ON comments (article_id);
CREATE INDEX index_categories_on_parent_id ON categories (parent_id);
CREATE INDEX index_likes_on_likeable ON likes (likeable_type, likeable_id);
CREATE TABLE authors (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE profiles (
  id UUID PRIMARY KEY,
  author_id UUID NOT NULL REFERENCES authors (id),
  bio TEXT
);
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  author_id UUID NOT NULL REFERENCES authors (id),
  title TEXT NOT NULL,
  published BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE comments (
  id UUID PRIMARY KEY,
  article_id UUID NOT NULL REFERENCES articles (id),
  body TEXT NOT NULL
);
CREATE TABLE categories (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  parent_id UUID REFERENCES categories (id)
);
CREATE TABLE photos (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL
);
CREATE TABLE videos (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL
);
CREATE TABLE likes (
  id UUID PRIMARY KEY,
  likeable_type TEXT NOT NULL,
  likeable_id UUID NOT NULL
);
CREATE INDEX index_profiles_on_author_id ON profiles (author_id);
CREATE INDEX index_articles_on_author_id ON articles (author_id);
CREATE INDEX index_comments_on_article_id ON comments (article_id);
CREATE INDEX index_categories_on_parent_id ON categories (parent_id);
CREATE INDEX index_likes_on_likeable ON likes (likeable_type, likeable_id);

Defining associations

Declare each association as a field, passing the target Model’s class, as the Models above do:

  • The field’s name is the association’s name.
  • Models can refer to each other in any order.
  • A subclass inherits its parent’s associations, and can redeclare one to change it.

belongsTo

Use belongsTo on the Model whose table holds the foreign key, as an article belongs to its author:

import { class ArticleArticle } from "./models/article";
import { class AuthorAuthor } from "./models/author";

const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "On Nothing" });
const const author: Author | nullauthor = await const article: Articlearticle.
Article.author: BelongsTo
() => Promise<Author | null>
author
(); // an Author, or null
const const other: Authorother = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Sam" });
const article: Articlearticle.Article.author: BelongsTo<typeof Author>author.BelongsTo<typeof Author>.set(record: Author | null): voidset(const other: Authorother); // written when the article is saved await const article: Articlearticle.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
();
  • await record.author() reads the associated record, or null.
  • record.author.set(user) points the record at another record, and set(null) clears it. It’s written when the record is saved.
  • record.author.build(attrs) builds a record to point at. It’s validated with the record, and saved before it, so the foreign key can be filled in.
  • record.author.create(attrs) and createOrThrow(attrs) save a new record at once, and point at it. The record itself isn’t saved.
Option Does
foreignKey The attribute on this record that holds the link. Defaults to the association’s name + Id
primaryKey The attribute on the target it points at. Defaults to the target’s primary key
scope Narrows the target, (q) => q.where(…). See Scoping associations
optional Lets the record point at nothing. See Requiring the record
autosave true saves the record’s changes with this record. See Saving changed records
inverseOf The target’s hasOne that points back, or false. See Inverse associations

Requiring the record

Saving a record checks that each belongsTo points at a record that exists, unless it’s declared optional: true, as a category’s parent is:

  • If the foreign key is null, or no row has that key, the save fails with “must exist” on the association, such as author. The record it finds stays loaded.
  • A saved record whose foreign key hasn’t changed isn’t checked again.
  • A record built through a hasMany or hasOne already points at its owner, so it passes the check before either is saved. See Autosaving.

hasMany

Use hasMany on the Model the other table’s foreign key points at, as an author has many articles:

import { class AuthorAuthor } from "./models/author";

const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
const const articles: Article[]articles = await const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().Relation<Article, ScopesOf<typeof Article>>.toArray(): Promise<Article[]>toArray(); // a Relation of the author's articles const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().
Relation<Article, ScopesOf<typeof Article>>.build(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly published: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: ((record: Article) => void) | undefined): Article
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ title?: string | undefinedtitle: "Untitled" }); // saved with the author, with its key
await const author: Authorauthor.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
();
await const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().Relation<Article, ScopesOf<typeof Article>>.where(conditions: SafeSql | Conditions<Article>): Relation<Article, ScopesOf<typeof Article>>where({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Untitled" }).Relation<Article, ScopesOf<typeof Article>>.deleteAll(): Promise<number>
Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL instead unless its `dependent:` deletes. A `none()` Relation sends nothing and resolves to 0.
deleteAll
(); // scoped to the author's articles
  • record.articles() is a Relation of the associated records, with every Relation method and the target’s scopes.
  • record.articles().build(attrs) builds a record with the owner’s key, saved with the owner. See Autosaving.
  • record.articles().create(attrs) and createOrThrow(attrs) save a new record at once. The owner must already be saved.
  • record.articles().push(...records) adds records. It sets their foreign key and saves them in one write, or resolves to false and saves none if one can’t be saved. On an unsaved owner, they’re saved with it.
  • record.articles().delete(...records) removes records by the dependent strategy. It destroys them for "destroy", deletes them for "deleteAll", and otherwise sets their foreign key to NULL.
  • record.articles().destroy(...records) destroys records with their callbacks, whatever the strategy.
  • record.articles().clear() removes every record, as deleteAll() does.
  • record.articles().destroyAll() destroys every record with its callbacks, whatever the strategy, and leaves the association empty.
Option Does
foreignKey The attribute on the target’s records that holds the link. Defaults to this Model’s class name + Id
primaryKey The attribute on this record the foreign key points at. Defaults to the primary key
scope Narrows or orders the records, (q) => q.order(…). See Scoping associations
dependent What destroying the owner does to the records. See Destroying dependent records
autosave true saves the records’ changes with the owner. See Saving changed records
inverseOf The target’s belongsTo that points back, or false. See Inverse associations

hasOne

Use hasOne like hasMany, when there’s at most one record, as an author has one profile:

import { class AuthorAuthor } from "./models/author";

const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
const const profile: Profile | nullprofile = await const author: Authorauthor.
Author.profile: HasOne
() => Promise<Profile | null>
profile
(); // a Profile, or null
if (const profile: Profile | nullprofile === null) await const author: Authorauthor.Author.profile: HasOne<typeof Profile>profile.
HasOne<typeof Profile>.create(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly bio: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined): Promise<Profile>
create
({ bio?: string | null | undefinedbio: "Writer" }); // saved at once
  • await record.profile() reads the associated record, or null. If several records point at the owner, it’s the first by the scope’s order, then the primary key.
  • await record.profile.set(profile) gives the owner another record, and set(null) removes it. On a saved owner, the record is saved at once, so await it. On an unsaved owner, it’s saved with the owner.
  • record.profile.build(attrs) builds a record with the owner’s key, saved with the owner.
  • record.profile.create(attrs) and createOrThrow(attrs) save a new record at once. The owner must already be saved.

hasOne takes the same options as hasMany.

Replacing the record

Giving a saved owner a new record removes its old one, by the association’s dependent strategy:

import { class AuthorAuthor } from "./models/author";
import { class ProfileProfile } from "./models/profile";

const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
await const author: Authorauthor.Author.profile: HasOne<typeof Profile>profile.HasOne<typeof Profile>.set(record: Profile | null): Promise<void>set(class ProfileProfile.
build<typeof Profile>(this: typeof Profile, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly bio: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Profile) => void) | undefined): Profile
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ bio?: string | null | undefinedbio: "Novelist" })); // and deletes the old one, in one batch
dependent What happens to the old record
"destroy" It’s destroyed, with its own callbacks
"delete" It’s deleted, without callbacks
"nullify", a restrict strategy, or none Its foreign key is set to NULL, and it’s saved
  • The old record is removed in the same atomic batch that writes the new one. That’s at once for set and create, and when the owner is saved for build.
  • If the old record can’t be saved with a NULL foreign key, the write throws RecordNotSaved, and nothing is written.
  • If the new record doesn’t save, the old one stays. set throws RecordNotSaved and leaves the association as it was. create returns the unsaved record, and saving the owner tries again.

Polymorphic associations

A polymorphic belongsTo points at a record of any of several Models, listed in an array, as a like belongs to a photo or a video:

import { class LikeLike } from "./models/like";
import { class VideoVideo } from "./models/video";

const const like: Likelike = await class LikeLike.firstOrThrow<typeof Like>(this: typeof Like): Promise<Like>
Like `first`, but throws `RecordNotFound` instead of returning null.
firstOrThrow
();
const const liked: Video | Photo | nullliked = await const like: Likelike.
Like.likeable: PolymorphicBelongsTo
() => Promise<Video | Photo | null>
likeable
(); // a Photo, a Video, or null
const const video: Videovideo = await class VideoVideo.findByOrThrow<typeof Video>(this: typeof Video, conditions: SafeSql | Conditions<Video>): Promise<Video>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Launch" });
const like: Likelike.Like.likeable: PolymorphicBelongsTo<typeof Video | typeof Photo>likeable.PolymorphicBelongsTo<typeof Video | typeof Photo>.set(record: Video | Photo | null): voidset(const video: Videovideo); // likeableType "Video", likeableId video.id await const like: Likelike.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
();
const const likes: Like[]likes = await const video: Videovideo.Video.likes: () => HasManyCollection<Like, ScopesOf<typeof Like>>likes().Relation<Like, ScopesOf<typeof Like>>.toArray(): Promise<Like[]>toArray(); // the likes whose type is "Video"
  • The record holds the link in two attributes: a type, which names the Model, and a foreign key. They’re the association’s name with Type and Id, so likeable uses likeableType and likeableId.
  • On each listed Model, a hasMany or hasOne names the belongsTo with as, and reads the records whose type is that Model.
  • await like.likeable() reads the record of the Model the type names, or null, and like.likeable.set(video) sets both the type and the foreign key. set(null) clears both.
  • video.likes() works like any hasMany. Records built, created, or pushed through it get the video’s type and key. Removing records through it, or by a "nullify" strategy, clears both.
  • To preload one, see Preloading polymorphic records.
Option Does
foreignType The attribute that holds the type. Defaults to the association’s name + Type, or on a hasMany or hasOne, the as name + Type
as On a hasMany or hasOne: the name of the target’s polymorphic belongsTo. Its foreign key defaults to that name + Id

The polymorphic belongsTo also takes foreignKey, primaryKey, optional, and autosave, as any belongsTo does. It has no build or create, since it can’t tell which Model to make, and no scope. Neither D1 nor Postgres can enforce a foreign key that points at a different table in each row.

Storing the type

The type holds the listed Model’s modelName, such as "Photo":

  • A subclass of a listed Model is stored as the Model whose table it shares.
  • If a stored type names none of the listed Models, reading the association throws UnknownModelName.

Naming foreign keys

A foreign key names an attribute, such as authorId, rather than a column, and by default it’s inferred:

  • belongsTo uses the association’s name + Id. author = belongsTo(Author) uses the record’s own authorId.
  • hasMany and hasOne use the Model’s name + Id, on the target. Author’s associations use authorId, BlogPost’s use blogPostId, and APIKey’s use apiKeyId.
  • If the name doesn’t follow the convention, pass foreignKey, as Category does with parentId.
  • Keys are checked the first time a Model is used, and a missing attribute throws InvalidModel. If a bundler renames Author to e, the inferred eId doesn’t exist; set static modelName (see Naming Models), pass foreignKey, or keep class names in your bundler’s settings.

Caching loaded records

A loaded association is cached on the record, so reading it again sends no query:

import { class ArticleArticle } from "./models/article";

const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "On Nothing" });
const const author: Author | nullauthor = await const article: Articlearticle.
Article.author: BelongsTo
() => Promise<Author | null>
author
(); // one query
const const again: Author | nullagain = await const article: Articlearticle.
Article.author: BelongsTo
() => Promise<Author | null>
author
(); // none: it's cached on the article
  • Changing a foreign key makes the next read query again.
  • reload() clears the cache, and await record.reloadAssociation("articles") reloads one association.
  • A write through a hasMany clears its loaded collection: insert, upsert, updateAll and deleteAll, alone or in db.batch, even after where or order, or with the association joined by or(), merge() or a scope. create, push, delete, destroy, and clear on the association itself update it instead, so the next read still doesn’t query.
  • A write made another way, such as Article.where({ authorId: author.id }).deleteAll(), doesn’t touch a loaded collection: reload the association to see it.
  • A belongsTo whose foreign key is null, or an association on an unsaved owner, reads without a query.

Inverse associations

A record loaded through its owner’s hasMany or hasOne has the owner loaded already, so reading it back sends no query:

import { class AuthorAuthor } from "./models/author";

const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
const [const article: Articlearticle] = await const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().Relation<Article, ScopesOf<typeof Article>>.toArray(): Promise<Article[]>toArray(); const const sameAuthor: Author | nullsameAuthor = await const article: Articlearticle?.
Article.author: BelongsTo
() => Promise<Author | null>
author
(); // author itself, with no query
  • Every record the association loads points back: from toArray(), first(), find(), findBy(), a Relation narrowed from it, and includes.
  • Records built or created through the association point back too, before either is saved.
  • A belongsTo’s record points back through its hasOne. After await profile.author(), the author’s profile() is that profile. A hasMany isn’t filled this way, because one record isn’t the whole collection.
  • The owner is the same object on both sides, so a change to it shows from either one. If the belongsTo is declared autosave: true, saving one of those records also saves the owner’s unsaved changes.
  • The inverse is the target’s first belongsTo that points at the owner’s Model through the same foreign key. None is found when either association has a scope, or for an association through another. Name it with inverseOf then, as publishedArticles does.
  • inverseOf on a hasMany or hasOne names a belongsTo, and on a belongsTo it names a hasOne. On a polymorphic belongsTo, each Model it lists needs that hasOne. inverseOf: false turns the inverse off. If the association you name doesn’t link back through the same keys, using the Model throws InvalidModel.

Scoping associations

Narrow or order an association’s records with scope, as Author’s publishedArticles does:

import { class AuthorAuthor } from "./models/author";

const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
const const published: Article[]published = await const author: Authorauthor.Author.publishedArticles: () => HasManyCollection<Article, ScopesOf<typeof Article>>publishedArticles().Relation<Article, ScopesOf<typeof Article>>.toArray(): Promise<Article[]>toArray(); // only the published ones
  • The scope applies to reads and preloads alike, and records created through the association take its equality values.
  • q is the target’s Relation, with its attributes and scopes. The target’s default scope applies too.
  • A scope that uses limit, offset, or distinct can’t be preloaded, since it would apply to every owner’s records together. includes throws IncompatibleRelation before it sends any preload.

Associating a Model with itself

Point a Model’s association at its own class, with its own foreign key, as Category does:

import { class CategoryCategory } from "./models/category";

const [const top: Categorytop] = await class CategoryCategory.Category.top: <typeof Category>(this: typeof Category) => Relation<Category, ScopesOf<typeof Category>> & ScopeMethods<Category, ScopesOf<typeof Category>>top().Relation<Category, ScopesOf<typeof Category>>.toArray(): Promise<Category[]>toArray();
const const children: Category[]children = await const top: Categorytop?.Category.children: () => HasManyCollection<Category, ScopesOf<typeof Category>>children().Relation<Category, ScopesOf<typeof Category>>.toArray(): Promise<Category[]>toArray(); // in name order, by the scope
const const parent: Category | nullparent = await const children: Category[]children?.[0]?.
Category.parent: BelongsTo
() => Promise<Category | null>
parent
(); // top itself

TypeScript can’t infer an association whose scope uses its own Model’s scopes, such as children ordered by alphabetical(), so write the field’s type out: HasMany<typeof Category>.

Destroying dependent records

Set what destroying the owner does to its records with dependent:

import { class AuthorAuthor } from "./models/author";

const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
await const author: Authorauthor.Model.destroy(): Promise<false | Author>
Deletes the row and resolves to this record, now a read-only destroyed snapshot. A row that's already gone still counts. `false` means a `beforeDestroy` or `aroundDestroy` callback aborted (or an `aroundDestroy` didn't call `next()`), or a `restrictWithError` association refused.
destroy
(); // its articles, their comments, and its profile go too, in one batch
Strategy What happens
"destroy" Each record is destroyed with its own callbacks and dependents
"deleteAll" / "delete" The records are deleted in one statement, without callbacks ("delete" for a hasOne)
"nullify" Their foreign keys are set to NULL
"restrictWithException" The destroy throws DeleteRestriction while there are records
"restrictWithError" The destroy returns false, with an error on the owner’s base
  • Everything a destroy does on the owner’s database, its DELETE included, is written in one atomic batch. Records on another database are written there separately.
  • Strategies run after the owner’s beforeDestroy callbacks, so an abort() leaves the records alone.
  • Without a strategy, it’s up to the database. If the table declares the foreign key with REFERENCES, destroying an owner whose records still point at it throws InvalidForeignKey.

Writing many rows

insert, updateAll, and deleteAll work through a hasMany, scoped to the owner’s records:

import { class ArticleArticle } from "./models/article";

const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "On Nothing" });
await const article: Articlearticle.Article.comments: () => HasManyCollection<Comment, ScopesOf<typeof Comment>>comments().Relation<Comment, ScopesOf<typeof Comment>>.deleteAll(): Promise<number>
Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL instead unless its `dependent:` deletes. A `none()` Relation sends nothing and resolves to 0.
deleteAll
(); // one DELETE for the article's comments
  • In a batch, pass the association to the write: b.deleteAll(article.comments()).
  • upsert and upsertAll through a hasMany only update the owner’s records. When a row clashes with another owner’s record, that record stays as it is. The row isn’t written, counted, or returned. To find out whether a row was skipped, compare rowsAffected with the number of rows you gave.
  • deleteAll() on the association follows its dependent strategy: it deletes the records for "destroy" or "deleteAll", and otherwise sets their foreign keys to NULL. See Bulk writes and batches.

Not built yet

These features aren’t in Active Record yet. The code shows the shape they’re likely to take.

  • Associations through another across databases (#435): an association whose hops are on different databases, read with a query per database.

Last updated on