---
title: Through associations
description: "Read and write records through a join Model, such as an article’s tags through its taggings."
seo:
  description: "Many-to-many associations in Active Record: hasMany and hasOne through a join Model, with source, preloading, push, build, create, and removing join records."
---

## 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

| Prop | Type | Default | Description |
| - | - | - | - |
| `through` | `string` | - | The association to go through. |
| `source?` | `string` | - | The join Model’s association to follow. Defaults to this association’s name, singular or plural. |
| `scope?` | `(q) => Relation` | - | Narrows or orders the records, as on any association. |
| `dependent?` | `"destroy" \| "deleteAll"` | - | What destroying the owner does to the join records. hasMany only. |

`scope` works as it does on any association. See [Scoping associations](/associations#scoping-associations).

## 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 } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";

export class Author extends ApplicationRecord {
  articles = hasMany(Article);
}
```

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

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

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

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

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

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

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

const tag = await Tag.findByOrThrow({ name: "essays" });
const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query

const article = await Article.findByOrThrow({ title: "Engines" });
const tags = await article.tags().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](#writing-through-it).
- 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`:

```ts
import { Tag } from "./models/tag";

const everyTag = await Tag.includes("articles").toArray(); // tags, taggings, and articles
for (const each of everyTag) console.log(each.name, each.loaded("articles").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`:

```ts
import { Tag } from "./models/tag";

const tag = await Tag.findByOrThrow({ name: "essays" });
const writers = await tag.writers().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`:

```ts
import { Tagging } from "./models/tagging";

const tagging = await Tagging.firstOrThrow();
const author = await tagging.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:

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

const tag = await Tag.findByOrThrow({ name: "essays" });
const article = await Article.findByOrThrow({ title: "Engines" });

await tag.articles().push(article); // saves a tagging that links them
const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" });

await tag.articles().delete(article); // 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.

:::warning[A narrowed deleteAll or destroyAll removes the records themselves]
`updateAll`, and a narrowed `deleteAll` or `destroyAll`, act on the records, as any Relation’s do. `tag.articles().where({ title: "Draft" }).deleteAll()` deletes those articles for every tag, not 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.

:::note
Every association it goes through must be on one database. One that reaches [another database](/several-databases#associating-models-on-different-databases) is an `InvalidModel` for now ([#435](https://github.com/forestfuture/active-record/issues/435)).
:::

> **Compared with Rails**
>
> `through` and `source` work as Rails’ `has_many :through` and `has_one :through` options do. Rails reads through a SQL join, so a record two join records point at comes back twice unless the association is `distinct`. Here it comes back once.
>
> Writing through it works as in Rails: `destroy` destroys the join records rather than the records, `clear` deletes them whatever `dependent` is, and `insert_all` through it raises. Rails also writes through a `belongsTo` or `hasOne` hop by building or updating that hop’s record, which can change a record that other records share. Here that throws `ReadonlyAssociation`. Rails’ `disable_joins` has no counterpart yet.
