Database

Relations and Eager Loading

Declare HasOne, HasMany, BelongsTo and ManyToMany relations on AxilJS entities and eager-load them with with() in one batched query per relation, no N+1.

4 min readUpdated DocumentationEdit this page
On this page9

Relations in @axiljs/orm are declared with four property decorators and loaded explicitly with with(). Each relation is fetched with one batched WHERE key IN (...) query for all parent records, so loading posts for 100 users costs one extra query, not 100.

TypeScript
TS
1import { Entity, PrimaryKey, Column, HasMany, BelongsTo, BaseModel } from '@axiljs/orm'
2
3@Entity('users')
4class User extends BaseModel {
5  @PrimaryKey() id!: number
6  @Column() name!: string
7
8  @HasMany(() => Post) posts!: Post[]
9}
10
11@Entity('posts')
12class Post extends BaseModel {
13  @PrimaryKey() id!: number
14  @Column() title!: string
15  @Column() user_id!: number
16
17  @BelongsTo(() => User) user!: User | null
18}
19
20const users = await User.with('posts').get()

The target is passed as a factory (() => Post) so two entities can reference each other regardless of declaration order.

Relation decorators

DecoratorStored on the parent asKey lives on
@HasOne(() => Target, options?)the related record or nullthe related table
@HasMany(() => Target, options?)an array (empty when none)the related table
@BelongsTo(() => Target, options?)the related record or nullthis table
@ManyToMany(() => Target, options?)an array (empty when none)a pivot table

Options

OptionApplies toMeaning
foreignKeyallhasOne/hasMany: column on the related table pointing at this entity. belongsTo: column on this table pointing at the related entity. manyToMany: pivot column pointing at this entity.
pivotTablemanyToManyName of the pivot table
relatedKeymanyToManyPivot column pointing at the related entity
eagerallRecorded in metadata only. Relations are never loaded automatically; call with().

Default key names

Defaults are derived from class names in snake_case (BlogPost → blog_post), not table names:

RelationDefault
hasOne / hasManyforeignKey: <parent_class>_id on the related table
belongsToforeignKey: <related_class>_id on this table
manyToManypivotTable: both class names, sorted, joined by _ (Post + Tag → post_tag)
manyToManyforeignKey: <parent_class>_id, relatedKey: <related_class>_id

Keys are matched against the primary key declared with @PrimaryKey() on each entity.

TypeScript
TS
1@Entity('articles')
2class Article extends BaseModel {
3  @PrimaryKey() id!: number
4
5  // articles.author_id → users.id
6  @BelongsTo(() => User, { foreignKey: 'author_id' }) author!: User | null
7
8  // article_tags(article_id, tag_id)
9  @ManyToMany(() => Tag, { pivotTable: 'article_tags' }) tags!: Tag[]
10}

Loading relations

There are four entry points, all backed by the same loader.

TypeScript
TS
1// 1. Query builder: Model.with(...) or Model.query().with(...)
2const users = await User.with('posts').where('active', '=', true).get()
3
4// 2. find() / all() options
5const user  = await User.find(1, { with: ['posts'] })
6const all   = await User.all({ with: ['posts'] })
7
8// 3. On an instance you already have
9await user!.load('posts')
10
11// 4. Repositories
12const rows = await userRepo.find({ active: true }, { with: ['posts'] })
13const one  = await userRepo.findById(1, { with: ['posts'] })

When the related entity extends BaseModel, find(), all() and load() hydrate related rows into model instances. Through the query builder and repositories they stay plain rows.

Nested relations

Use dot paths. Each level is one more batched query.

TypeScript
TS
const users = await User.with('posts', 'posts.comments').get()
// users[0].posts[0].comments → Comment[]

Soft deletes

If the related entity has a @DeletedAt column, soft-deleted related rows are excluded from eager loads.

How batching works

For User.with('posts') on 250 users the loader runs:

SQL
SQL
SELECT * FROM users WHERE ...;
SELECT * FROM posts WHERE user_id IN (1, 2, ..., 250);

Large key lists are split into chunks of 500 to stay below every driver's bind-parameter limit. Duplicate and null keys are skipped. A manyToMany load joins the pivot table in the same query.

Low-level: eagerLoad()

eagerLoad is exported for custom data layers. It mutates the records you pass in, storing each relation under its property name.

TypeScript
TS
1import { eagerLoad } from '@axiljs/orm'
2
3await eagerLoad(User, rows, ['posts'], {
4  driver: db.getDriver(),
5  driverType: 'postgres',
6  hydrate: (target, row) => row  // optional: convert related rows
7})

An unknown relation name throws Unknown relation "<name>" on <Class>. A relation whose target lacks @Entity throws as well.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY