---
title: Associations
description: "Connect Models with belongsTo, hasMany, and hasOne."
seo:
  description: "Connect Active Record Models with belongsTo, hasMany, and hasOne: reading and setting records, polymorphic associations, foreign keys, scopes, and dependents."
---

## 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](/preloading)                     |
| save records with their owner                     | [Autosaving](/autosaving)                     |
| reach records through another association         | [Through associations](/through-associations) |
| keep a count of a record’s associated records     | [Counter caches](/counter-caches)             |
| set `updatedAt` when an associated record changes | [Touching](/touching)                         |
| filter by associated records                      | [Joins](/joins)                               |

## The Models

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

```ts author.ts
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",
  });
}
```

```ts article.ts
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
}
```

```ts profile.ts
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Author } from "./author";

export class Profile extends ApplicationRecord {
  author = belongsTo(Author);
}
```

```ts comment.ts
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";

export class Comment extends ApplicationRecord {
  article = belongsTo(Article);
}
```

```ts category.ts
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(),
  });
}
```

```ts like.ts
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
}
```

```ts photo.ts
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"
}
```

```ts video.ts
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"
}
```

```ts schema.ts
// 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"]> {}
}
```

```sql D1
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);
```

```sql Postgres
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:

```ts
import { Article } from "./models/article";
import { Author } from "./models/author";

const article = await Article.findByOrThrow({ title: "On Nothing" });
const author = await article.author(); // an Author, or null

const other = await Author.findByOrThrow({ name: "Sam" });
article.author.set(other); // written when the article is saved
await article.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](#scoping-associations)                            |
| `optional`   | Lets the record point at nothing. See [Requiring the record](#requiring-the-record)                                   |
| `autosave`   | `true` saves the record’s changes with this record. See [Saving changed records](/autosaving#saving-changed-records) |
| `inverseOf`  | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#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](/autosaving#saving-a-graph).

## hasMany

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

```ts
import { Author } from "./models/author";

const author = await Author.findByOrThrow({ name: "Jane" });
const articles = await author.articles().toArray(); // a Relation of the author's articles

author.articles().build({ title: "Untitled" }); // saved with the author, with its key
await author.save();

await author.articles().where({ title: "Untitled" }).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](/autosaving#saving-a-graph).
- **`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](#scoping-associations)               |
| `dependent`  | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records)    |
| `autosave`   | `true` saves the records’ changes with the owner. See [Saving changed records](/autosaving#saving-changed-records) |
| `inverseOf`  | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#inverse-associations)            |

## hasOne

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

```ts
import { Author } from "./models/author";

const author = await Author.findByOrThrow({ name: "Jane" });
const profile = await author.profile(); // a Profile, or null
if (profile === null) await author.profile.create({ bio: "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:

```ts
import { Author } from "./models/author";
import { Profile } from "./models/profile";

const author = await Author.findByOrThrow({ name: "Jane" });
await author.profile.set(Profile.build({ bio: "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:

```ts
import { Like } from "./models/like";
import { Video } from "./models/video";

const like = await Like.firstOrThrow();
const liked = await like.likeable(); // a Photo, a Video, or null

const video = await Video.findByOrThrow({ title: "Launch" });
like.likeable.set(video); // likeableType "Video", likeableId video.id
await like.save();

const likes = await video.likes().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](/preloading#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`.

:::warning[Set modelName if your bundler renames classes]
The type is saved in your rows. A Model’s name is its class name unless it sets `static modelName`, so a bundler that renames `Photo` to `e` saves `"e"`, and a later build can’t read those rows. Wrangler keeps class names by default. With any other bundler, set `static modelName` on each listed Model. See [Naming Models](/models#naming-models).
:::

## 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](/models#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:

```ts
import { Article } from "./models/article";

const article = await Article.findByOrThrow({ title: "On Nothing" });
const author = await article.author(); // one query
const again = await article.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:

```ts
import { Author } from "./models/author";

const author = await Author.findByOrThrow({ name: "Jane" });
const [article] = await author.articles().toArray();
const sameAuthor = await article?.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`](/preloading).
- 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](/through-associations). 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:

```ts
import { Author } from "./models/author";

const author = await Author.findByOrThrow({ name: "Jane" });
const published = await author.publishedArticles().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](/scopes#narrowing-every-query) 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:

```ts
import { Category } from "./models/category";

const [top] = await Category.top().toArray();
const children = await top?.children().toArray(); // in name order, by the scope
const parent = await children?.[0]?.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`:

```ts
import { Author } from "./models/author";

const author = await Author.findByOrThrow({ name: "Jane" });
await author.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](/several-databases#associating-models-on-different-databases) 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:

```ts
import { Article } from "./models/article";

const article = await Article.findByOrThrow({ title: "On Nothing" });
await article.comments().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](/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](https://github.com/forestfuture/active-record/issues/435)): an association whose hops are on different databases, read with a query per database.

> **Compared with Rails**
>
> Rails requires a `belongs_to` record by default too, and `optional: true` works the same. As in Rails 7.1, an unchanged foreign key isn’t checked. There’s no setting to turn the check off for every association, like Rails’ `belongs_to_required_by_default`.
>
> `await user.profile.set(profile)` is Rails’ `user.profile = profile`. Rails removes the old record as soon as you build a new one, so a build that’s never saved still loses it. Here, `build` waits for the owner’s save.
>
> Rails declares `belongs_to :likeable, polymorphic: true` without a list, and finds the class from the stored name. Here you list the Models, so `await like.likeable()` is typed `Photo | Video | null`. Records built through `video.likes()` point back at the video without a query, which Rails doesn’t do for a polymorphic association.

> **Beyond Rails**
>
> After `author.articles().where({ title: "Untitled" }).deleteAll()`, `author.articles()` no longer holds the untitled articles. In Rails it still does, until you reload: only a write on the association itself resets what it has loaded. In Active Record any write built from `author.articles()` clears it, at the cost of one query on the next read.
>
> Rails finds an inverse by its name, and finds none when you pass `foreign_key:` or name the `belongs_to` otherwise. Active Record finds the inverse by its foreign key, so it finds `writer = belongsTo(Author, { foreignKey: "authorId" })` too, and a polymorphic `belongsTo`’s `hasOne` without `inverseOf`.
>
> In Rails, `upsert_all` through an association writes the owner’s key into a clashing row. So `current_user.posts.upsert_all(rows)`, given an id from a request, moves another user’s post to the current user. Here that row is skipped, as `onDuplicate: "skip"` skips a duplicate.
