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

Through associations

Read and write records through a join Model, such as an article’s tags through its taggings.

At a glance

To Write
declare a many-to-many association hasMany(Article, { through: "taggings" })
follow an association with another name hasMany(Author, { through: "articles", source: "author" })
reach one record hasOne(Author, { through: "article" })
read the records tag.articles(), a Relation
preload them Tag.includes("articles")
link a record tag.articles().push(article)
create a record and link it tag.articles().create({ … })
unlink a record tag.articles().delete(article)

Options

PropType
throughstring

The association to go through.

Typestring
source?string

The join Model’s association to follow. Defaults to this association’s name, singular or plural.

Typestring
scope?(q) => Relation

Narrows or orders the records, as on any association.

Type(q) => Relation
dependent?"destroy" | "deleteAll"

What destroying the owner does to the join records. hasMany only.

Type"destroy" | "deleteAll"

scope works as it does on any association. See Scoping associations.

The Models

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

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

export class Author extends ApplicationRecord {
  articles = hasMany(Article);
}
import { belongsTo, hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Author } from "./author";
import { Tag } from "./tag";
import { Tagging } from "./tagging";

export class Article extends ApplicationRecord {
  author = belongsTo(Author);
  taggings = hasMany(Tagging);
  tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
}
import { hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";
import { Author } from "./author";
import { Tagging } from "./tagging";

export class Tag extends ApplicationRecord {
  taggings = hasMany(Tagging);
  articles = hasMany(Article, { through: "taggings" }); // each tagging's article
  writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
}
import { belongsTo, hasOne } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";
import { Author } from "./author";
import { Tag } from "./tag";

export class Tagging extends ApplicationRecord {
  article = belongsTo(Article);
  tag = belongsTo(Tag);
  author = hasOne(Author, { through: "article" }); // the article's author
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 37e9b66aad51

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 },
} 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;

/** taggings — last changed by 0001_create_tables.sql */
export const taggings = {
  id: { type: "integer", null: false },
  articleId: { type: "string", null: false },
  tagId: { type: "integer", null: false },
} as const;

/** tags — last changed by 0001_create_tables.sql */
export const tags = {
  id: { type: "integer", null: false },
  name: { 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" },
    taggings: { attributes: taggings, primaryKey: "id" },
    tags: { attributes: tags, primaryKey: "id" },
  },
  models: { Article: "articles", Author: "authors", Tag: "tags", Tagging: "taggings" },
});

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/tag" {
  interface Tag extends TableAttributes<typeof tags, (typeof Tag)["attributes"]> {}
}

declare module "../models/tagging" {
  interface Tagging extends TableAttributes<typeof taggings, (typeof Tagging)["attributes"]> {}
}
CREATE TABLE authors (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL
);
CREATE TABLE articles (
  id TEXT PRIMARY KEY NOT NULL,
  author_id TEXT NOT NULL REFERENCES authors (id),
  title TEXT NOT NULL
);
CREATE TABLE tags (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE taggings (
  id INTEGER PRIMARY KEY,
  article_id TEXT NOT NULL REFERENCES articles (id),
  tag_id INTEGER NOT NULL REFERENCES tags (id)
);
CREATE TABLE authors (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  author_id UUID NOT NULL REFERENCES authors (id),
  title TEXT NOT NULL
);
CREATE TABLE tags (
  id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE taggings (
  id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  article_id UUID NOT NULL REFERENCES articles (id),
  tag_id BIGINT NOT NULL REFERENCES tags (id)
);

Reading records

Read a through association as you would any hasMany:

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

const const tag: Tagtag = await class TagTag.findByOrThrow<typeof Tag>(this: typeof Tag, conditions: SafeSql | Conditions<Tag>): Promise<Tag>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "essays" });
const const articles: Article[]articles = await const tag: Tagtag.
Tag.articles: () => Relation<Article, ScopesOf<typeof Article>> & CollectionMethods<Article> & {
    readonly insert: never;
    readonly insertAll: never;
    readonly upsert: never;
    readonly upsertAll: never;
}
articles
().Relation<Article, ScopesOf<typeof Article>>.order(spec: SafeSql | OrderSpec<Article>): Relation<Article, ScopesOf<typeof Article>>
Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc", nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
order
({
title?: OrderDirection | {
    direction: OrderDirection;
    nulls?: NullsPlacement;
} | undefined
title
: "asc" }).Relation<Article, ScopesOf<typeof Article>>.toArray(): Promise<Article[]>toArray(); // one query
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: "Engines" });
const const tags: Tag[]tags = await const article: Articlearticle.
Article.tags: () => Relation<Tag, ScopesOf<typeof Tag>> & CollectionMethods<Tag> & {
    readonly insert: never;
    readonly insertAll: never;
    readonly upsert: never;
    readonly upsertAll: never;
}
tags
().Relation<Tag, ScopesOf<typeof Tag>>.toArray(): Promise<Tag[]>toArray(); // the other way, through the same taggings
  • through names one of the Model’s own associations, here taggings. The join Model’s association with the same name, singular or plural, leads on to the records: articles follows each tagging’s article.
  • tag.articles() is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as below.
  • Each record comes back once, however many join records point at it.
  • The scopes of both associations it goes through apply, and so does its own scope.

Preloading records

Preload the records for every tag with includes:

import { class TagTag } from "./models/tag";

const const everyTag: Tag[]everyTag = await class TagTag.
includes<typeof Tag>(this: typeof Tag, ...args: (AssociationName<Tag> | {
    readonly articles?: AssociationName<Article> | {
        readonly taggings?: AssociationName<Tagging> | {
            readonly author?: "articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            } | readonly ("articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            })[] | undefined;
            readonly article?: AssociationName<...> | ... 2 more ... | undefined;
            readonly tag?: AssociationName<...> | ... 2 more ... | undefined;
        } | readonly (AssociationName<...> | {
            readonly author?: "articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            } | readonly ("articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            })[] | undefined;
            readonly article?: AssociationName<...> | ... 2 more ... | undefined;
            readonly tag?: AssociationName<...> | ... 2 more ... | undefined;
        })[] | undefined;
        readonly tags?: AssociationName<...> | ... 2 more ... | undefined;
        readonly author?: "articles" | ... 2 more ... | undefined;
    } | readonly (AssociationName<...> | {
        readonly taggings?: AssociationName<Tagging> | {
            readonly author?: "articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            } | readonly ("articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            })[] | undefined;
            readonly article?: AssociationName<...> | ... 2 more ... | undefined;
            readonly tag?: AssociationName<...> | ... 2 more ... | undefined;
        } | readonly (AssociationName<...> | {
            readonly author?: "articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            } | readonly ("articles" | {
                readonly articles?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
            })[] | undefined;
            readonly article?: AssociationName<...> | ... 2 more ... | undefined;
            readonly tag?: AssociationName<...> | ... 2 more ... | undefined;
        })[] | undefined;
        readonly tags?: AssociationName<...> | ... 2 more ... | undefined;
        readonly author?: "articles" | ... 2 more ... | undefined;
    })[] | undefined;
    readonly taggings?: AssociationName<...> | ... 2 more ... | undefined;
    readonly writers?: "articles" | ... 2 more ... | undefined;
})[]): Relation<...>
Preloads associations for every record this Relation loads, so reading them afterwards sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
includes
("articles").Relation<Tag, ScopesOf<typeof Tag>>.toArray(): Promise<Tag[]>toArray(); // tags, taggings, and articles
for (const const each: Tageach of const everyTag: Tag[]everyTag) var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const each: Tageach.name: stringname, const each: Tageach.Model.loaded<"articles">(name: "articles"): Article[]
A loaded association, synchronously: records for a hasMany, a record or null otherwise. Throws `AssociationNotLoaded` unless it was preloaded with `includes(...)` or already read (and its key hasn't changed since).
loaded
("articles").Array<T>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length
);

The join records and the articles load with the tags’ own query, in one round trip on D1. The join records aren’t kept as taggings unless you include them too.

Naming the source

If the join Model’s association has another name, pass it as source, as writers does to follow each article’s author:

import { class TagTag } from "./models/tag";

const const tag: Tagtag = await class TagTag.findByOrThrow<typeof Tag>(this: typeof Tag, conditions: SafeSql | Conditions<Tag>): Promise<Tag>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "essays" });
const const writers: Author[]writers = await const tag: Tagtag.
Tag.writers: () => Relation<Author, ScopesOf<typeof Author>> & CollectionMethods<Author> & {
    readonly insert: never;
    readonly insertAll: never;
    readonly upsert: never;
    readonly upsertAll: never;
}
writers
().Relation<Author, ScopesOf<typeof Author>>.toArray(): Promise<Author[]>toArray(); // each author once

writers goes through articles, which goes through taggings. An association can go through any number of others this way.

Going through a belongsTo or a hasOne

A hasOne can go through a belongsTo, as a tagging’s author does through its article:

import { class TaggingTagging } from "./models/tagging";

const const tagging: Taggingtagging = await class TaggingTagging.firstOrThrow<typeof Tagging>(this: typeof Tagging): Promise<Tagging>
Like `first`, but throws `RecordNotFound` instead of returning null.
firstOrThrow
();
const const author: Author | nullauthor = await const tagging: Taggingtagging.
Tagging.author: HasOneThrough
() => Promise<Author | null>
author
();

through can name a belongsTo, a hasMany, or a hasOne, and the association it follows can be any of the three. A hasOne goes through a belongsTo or a hasOne.

Writing through it

Add records with push, build, and create, which each make the join record that links the owner to the record:

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

const const tag: Tagtag = await class TagTag.findByOrThrow<typeof Tag>(this: typeof Tag, conditions: SafeSql | Conditions<Tag>): Promise<Tag>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "essays" });
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: "Engines" });
await const tag: Tagtag.
Tag.articles: () => Relation<Article, ScopesOf<typeof Article>> & CollectionMethods<Article> & {
    readonly insert: never;
    readonly insertAll: never;
    readonly upsert: never;
    readonly upsertAll: never;
}
articles
().CollectionMethods<Article>.push(...records: Article[]): Promise<boolean>
Adds records to the association: sets each one's foreign key and saves them together, resolving to `false`, with nothing written, if one can't be saved.
push
(const article: Articlearticle); // saves a tagging that links them
const const draft: Articledraft = await const tag: Tagtag.
Tag.articles: () => Relation<Article, ScopesOf<typeof Article>> & CollectionMethods<Article> & {
    readonly insert: never;
    readonly insertAll: never;
    readonly upsert: never;
    readonly upsertAll: never;
}
articles
().
Relation<Article, ScopesOf<typeof Article>>.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 title: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: Init<Article> | undefined): Promise<Article>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or not it was saved (check `isPersisted()`).
create
({ authorId?: string | undefinedauthorId: const article: Articlearticle.authorId: stringauthorId, title?: string | undefinedtitle: "Draft" });
await const tag: Tagtag.
Tag.articles: () => Relation<Article, ScopesOf<typeof Article>> & CollectionMethods<Article> & {
    readonly insert: never;
    readonly insertAll: never;
    readonly upsert: never;
    readonly upsertAll: never;
}
articles
().CollectionMethods<Article>.delete(...records: Article[]): Promise<Article[]>
Removes records from the association by its `dependent:` strategy: destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and otherwise sets their foreign key to NULL. Resolves to the records.
delete
(const article: Articlearticle); // deletes the tagging; the article stays
  • push(article) saves a tagging for each article, in one write. A new article is saved first.
  • build(attributes) builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging.
  • create(attributes) saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written.

On a tag that isn’t saved yet, push and build wait for the tag’s save. create throws RecordNotSaved there, as it does through a hasMany.

Records built or created through it take the equality values of its scope, and their join records take those of the association it goes through.

Removing records

Removing records through the association removes their join records. The records themselves stay:

Method Does
delete(article) Deletes the tag’s taggings to the article, without callbacks
destroy(article) Destroys those taggings, running their callbacks, in one write
clear() Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded
deleteAll() Deletes the same taggings, and resolves to how many it deleted
destroyAll() Destroys the same taggings, running their callbacks, and resolves to the articles

An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: await article.destroy(). In a batch, pass the association to the write: b.deleteAll(tag.articles()) deletes the tag’s taggings.

Removing join records with dependent

A hasMany through a join Model takes dependent: "destroy" or dependent: "deleteAll", which acts on its join records:

  • With "destroy", destroying the tag destroys its taggings, running their callbacks, and delete destroys them too.
  • With "deleteAll", destroying the tag deletes them without callbacks.
  • clear and deleteAll always delete them without callbacks.

Setting a hasOne through another

A hasOne that goes through another hasOne has set, and no build or create:

  • set(record) points the owner’s join record at the record, or creates the join record if there isn’t one, with the equality values of the join association’s scope.
  • set(null) destroys the join record.

Spotting read-only associations

Writes need a join Model: the association has to go through a hasMany (a hasOne, for a hasOne), and follow a belongsTo from there, with neither going through another. Any other write throws ReadonlyAssociation, naming the association that stops it. writers is read-only, since it goes through articles, which goes through taggings.

insert, insertAll, upsert, and upsertAll throw ReadonlyAssociation on any association through another, since they write no join records.

Last updated on