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

Preloading

Load an association for many records at once, also called eager loading, with one query per association.

At a glance

To Write
preload an association Author.includes("profile")
preload several Author.includes("profile", "articles")
preload nested associations includes({ articles: "comments" }), includes({ articles: ["comments", "tags"] })
preload a polymorphic association Like.includes("likeable")
read a preloaded association, with no query author.loaded("profile")
check whether it’s loaded author.isLoaded("profile")

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);
  profile = hasOne(Profile);
}
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, 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);
  comments = hasMany(Comment);
}
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 } 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: 9e181a91394e

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;

/** 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" },
    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",
    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/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
);
CREATE TABLE comments (
  id TEXT PRIMARY KEY NOT NULL,
  article_id TEXT NOT NULL REFERENCES articles (id),
  body TEXT NOT NULL
);
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_articles_on_author_id ON articles (author_id);
CREATE INDEX index_comments_on_article_id ON comments (article_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
);
CREATE TABLE comments (
  id UUID PRIMARY KEY,
  article_id UUID NOT NULL REFERENCES articles (id),
  body TEXT NOT NULL
);
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_articles_on_author_id ON articles (author_id);
CREATE INDEX index_comments_on_article_id ON comments (article_id);

Preloading associations

Load an association for every record at once with includes, one query per association however many records there are:

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

const const authors: Author[]authors = await class AuthorAuthor.
includes<typeof Author>(this: typeof Author, ...args: (AssociationName<Author> | {
    readonly profile?: "author" | {
        readonly author?: AssociationName<Author> | ... | readonly (AssociationName<Author> | ...)[] | undefined;
    } | readonly ("author" | {
        readonly author?: AssociationName<Author> | ... | readonly (AssociationName<Author> | ...)[] | undefined;
    })[] | undefined;
    readonly articles?: AssociationName<Article> | {
        readonly comments?: "article" | {
            readonly article?: AssociationName<Article> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        } | readonly ("article" | {
            readonly article?: AssociationName<Article> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        })[] | undefined;
        readonly author?: AssociationName<...> | ... 2 more ... | undefined;
    } | readonly (AssociationName<...> | {
        readonly comments?: "article" | {
            readonly article?: AssociationName<Article> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        } | readonly ("article" | {
            readonly article?: AssociationName<Article> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        })[] | undefined;
        readonly author?: AssociationName<...> | ... 2 more ... | undefined;
    })[] | 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
("profile", {
articles?: AssociationName<Article> | {
    readonly comments?: "article" | {
        readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
    } | readonly ("article" | {
        readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
    })[] | undefined;
    readonly author?: AssociationName<Author> | {
        readonly profile?: "author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        } | readonly ("author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        })[] | undefined;
        readonly articles?: AssociationName<...> | ... 2 more ... | undefined;
    } | readonly (AssociationName<...> | {
        readonly profile?: "author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        } | readonly ("author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        })[] | undefined;
        readonly articles?: AssociationName<...> | ... 2 more ... | undefined;
    })[] | undefined;
} | readonly (AssociationName<...> | {
    readonly comments?: "article" | {
        readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
    } | readonly ("article" | {
        readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
    })[] | undefined;
    readonly author?: AssociationName<Author> | {
        readonly profile?: "author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        } | readonly ("author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        })[] | undefined;
        readonly articles?: AssociationName<...> | ... 2 more ... | undefined;
    } | readonly (AssociationName<...> | {
        readonly profile?: "author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        } | readonly ("author" | {
            readonly author?: AssociationName<Author> | ... | readonly (AssociationName<...> | ...)[] | undefined;
        })[] | undefined;
        readonly articles?: AssociationName<...> | ... 2 more ... | undefined;
    })[] | undefined;
})[] | undefined
articles
: "comments" }).Relation<Author, ScopesOf<typeof Author>>.toArray(): Promise<Author[]>toArray();
for (const const author: Authorauthor of const authors: Author[]authors) { 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(); // no query: already loaded 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 author: Authorauthor.name: stringname, const articles: Article[]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
, const author: Authorauthor.Model.loaded<"profile">(name: "profile"): Profile | null
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
("profile")?.bio: string | null | undefinedbio);
}
  • The example sends four queries, however many authors there are. On D1, the whole tree goes in one round trip with the authors’ own query. On Postgres, the queries run one after another. An association to another database takes one more.
  • author.loaded("profile") reads a preloaded association synchronously, and throws AssociationNotLoaded if it wasn’t loaded, so a template never sends a query. author.isLoaded("profile") checks first.
  • With a limit or offset, includes ends the order with the primary key, so the preloads find the same records the query loads.

Preloading polymorphic records

includes preloads a polymorphic association with one query for each listed Model:

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

const const likes: Like[]likes = await class LikeLike.
includes<typeof Like>(this: typeof Like, ...args: ("likeable" | {
    readonly likeable?: "likes" | {
        readonly likes?: "likeable" | ... | readonly ("likeable" | ...)[] | undefined;
    } | {
        readonly likes?: "likeable" | ... | readonly ("likeable" | ...)[] | undefined;
    } | readonly ("likes" | {
        readonly likes?: "likeable" | ... | readonly ("likeable" | ...)[] | undefined;
    } | {
        readonly likes?: "likeable" | ... | readonly ("likeable" | ...)[] | undefined;
    })[] | undefined;
})[]): Relation<Like, ScopesOf<typeof Like>>
Preloads associations for every record this Relation loads, so reading them afterwards sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
includes
("likeable").Relation<Like, ScopesOf<typeof Like>>.toArray(): Promise<Like[]>toArray(); // the likes, photos, and videos
for (const const like: Likelike of const likes: Like[]likes) { 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 like: Likelike.Model.loaded<"likeable">(name: "likeable"): Photo | Video | null
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
("likeable")?.title: string | undefinedtitle); // no query: already loaded
}
  • Each query runs the likes’ query again to find their keys, even for a Model no like points at. Index what that query filters and sorts by.
  • A nested include can name an association that only some listed Models have: includes({ likeable: "album" }) loads the photos’ albums and skips the videos.

Indexing what preloads read

Index each foreign key, as the migrations index author_id and article_id:

  • hasMany and hasOne find their records by the foreign key, both with includes and when you read one record’s association, such as author.articles(). Without an index, D1 reads every row of the table for each lookup, and bills you for each row it reads.
  • A references column from the generators is indexed already.
  • includes also runs the query’s own conditions again for each association it preloads, and with a limit or offset, its order. Index the columns the query filters and sorts by, too.

Last updated on