Relationships
Introduction
Database tables are usually related to one another: a user has many posts, a post belongs to a user, a user has many roles. Plinth models describe these relations in one place and give you three explicit ways to read them. This page covers defining every relation type, loading and querying them, aggregating over them, and changing related data.
The examples assume the connection setup from Getting Started:
import { Schema, sqliteConnection } from '@plinthjs/database'
import { ConnectionDataSource, Model } from '@plinthjs/orm'
const db = sqliteConnection()
Model.connection = db
Model.dataSource = new ConnectionDataSource(db)Relationships read through Model.dataSource. When you only set Model.connection, a ConnectionDataSource over it is used automatically, so the line above is optional (see Connecting a Model to a Database).
How Relationships Work
In a synchronous runtime a property read can quietly run a query. In Node it cannot: I/O is asynchronous, and any attempt to fake a blocking read breaks the event loop. Plinth therefore has no transparent lazy loading. A relation is never fetched by accident; you ask for it, and unloaded access fails loudly instead of firing a hidden query. The design is recorded in ADR 0003 (explicit async relationships) and ADR 0007 (the relationship API shape).
There are four patterns:
// 1. Eager: one query for the users, one for all of their posts.
const users = await User.query().with('posts').get()
// 2. Load onto a model you already have.
const user = (await User.query().first())!
await user.load('posts', 'profile')
// 3. Query the relation with constraints.
const published = await user.related('posts').where('published', true).get()
// 4. Read what was loaded. Throws RelationNotLoadedError if it was not.
user.getRelation('posts')Eager loading is batched. Loading posts for any number of users issues exactly two queries, and a nested path such as posts.comments issues one more query per level. That is how the API avoids N+1 queries.
Defining Relationships
A model declares its relations in the static relations map. Each entry is a function that receives the model instance and returns a relation. The key is the relation name you use everywhere else.
class User extends Model {
static override table = 'users'
static override fillable = ['name']
static override relations = {
posts: (model: Model) => model.hasMany(Post, 'user_id', 'id'),
profile: (model: Model) => model.hasOne(Profile, 'user_id', 'id'),
}
}
class Post extends Model {
static override table = 'posts'
static override fillable = ['title', 'published', 'votes']
static override relations = {
author: (model: Model) => model.belongsTo(User, 'user_id', 'id'),
comments: (model: Model) => model.hasMany(Comment, 'post_id'),
}
}
class Profile extends Model {
static override table = 'profiles'
static override fillable = ['bio']
}
class Comment extends Model {
static override table = 'comments'
static override fillable = ['body']
static override relations = {
post: (model: Model) => model.belongsTo(Post, 'post_id'),
}
}The tables used on this page:
const schema = new Schema(db)
await schema.create('users', (table) => {
table.id()
table.string('name')
table.timestamps()
})
await schema.create('profiles', (table) => {
table.id()
table.integer('user_id')
table.string('bio')
table.timestamps()
})
await schema.create('posts', (table) => {
table.id()
table.integer('user_id')
table.string('title')
table.boolean('published').default(false)
table.integer('votes').default(0)
table.timestamps()
})
await schema.create('comments', (table) => {
table.id()
table.integer('post_id').nullable()
table.string('body')
table.timestamps()
})Reading a loaded relation
Once a relation is loaded, read it with getRelation(). The bare relation name is also installed as a property on the model, so user.posts returns the loaded value and throws RelationNotLoadedError when nothing was loaded.
import { RelationNotLoadedError } from '@plinthjs/orm'
const user = (await User.query().first())!
try {
user.getRelation('posts')
} catch (error) {
error instanceof RelationNotLoadedError // => true
// Relation [posts] has not been loaded on [User]. Load it first with .with('posts') ...
}
await user.load('posts')
user.getRelation<Post[]>('posts').length // => 2
user.relationLoaded('posts') // => trueIn TypeScript, give the property a type with declare (a plain class field would shadow the generated getter) or write the getter yourself:
class Author extends Model {
static override table = 'users'
static override relations = {
posts: (model: Model) => model.hasMany(Post, 'user_id'),
}
declare posts: Post[]
// or: get posts(): Post[] { return this.getRelation<Post[]>('posts') }
}unsetRelation('posts') forgets a loaded relation, setRelation(name, value) sets one by hand, and refresh() clears all of them.
Relationship Types
One to many
hasMany(related, foreignKey, localKey = 'id'): the related table holds the foreign key. The loaded value is an array, empty when there are no children.
// posts.user_id references users.id
posts: (model: Model) => model.hasMany(Post, 'user_id')One to one
hasOne(related, foreignKey, localKey = 'id') is the single-result version. The loaded value is a model or null.
profile: (model: Model) => model.hasOne(Profile, 'user_id')The inverse: belongs to
belongsTo(related, foreignKey, ownerKey = 'id') is defined on the model that holds the foreign key. The loaded value is the owner or null.
author: (model: Model) => model.belongsTo(User, 'user_id', 'id')
const post = (await Post.query().with('author').first())!
post.getRelation<User>('author').getAttribute('name') // => 'Ann'Many to many
belongsToMany(related, pivotTable, foreignPivotKey, relatedPivotKey, parentKey = 'id', relatedKey = 'id') relates two models through a pivot table. foreignPivotKey is the pivot column that points at this model, and relatedPivotKey is the one that points at the related model.
await schema.create('roles', (table) => {
table.id()
table.string('name')
table.timestamps()
})
await schema.create('role_user', (table) => {
table.integer('user_id')
table.integer('role_id')
table.string('granted_by').nullable()
})
class Role extends Model {
static override table = 'roles'
static override fillable = ['name']
}
class Member extends Model {
static override table = 'users'
static override relations = {
roles: (model: Model) => model.belongsToMany(Role, 'role_user', 'user_id', 'role_id'),
}
}
const members = await Member.query().with('roles').get()
members[0]!.getRelation<Role[]>('roles').map((role) => role.getAttribute('name')) // => ['admin', 'editor']Eager loading runs two queries for any number of parents: one over the pivot table and one over the related table. See Pivot Tables for attaching and syncing.
Has many through
hasManyThrough(related, through, firstKey, secondKey, localKey = 'id', secondLocalKey = 'id') reaches distant models through an intermediate one. Here a user reaches comments through posts: posts.user_id points at the user, and comments.post_id points at the post.
class Writer extends Model {
static override table = 'users'
static override relations = {
comments: (model: Model) => model.hasManyThrough(Comment, Post, 'user_id', 'post_id'),
}
}
const writers = await Writer.query().with('comments').get()
writers[0]!.getRelation<Comment[]>('comments').length // => 1hasOneThrough takes the same arguments and loads a single model or null.
Polymorphic relations
A polymorphic relation lets one table belong to several others. The child table stores an id column and a type column, named ${name}_id and ${name}_type, and the type column holds the parent's morphClass(), which is the class name by default.
await schema.create('images', (table) => {
table.id()
table.string('url')
table.integer('imageable_id')
table.string('imageable_type')
table.timestamps()
})
class Image extends Model {
static override table = 'images'
static override fillable = ['url']
static override relations = {
// The morph map turns the stored type string into a model class.
imageable: (model: Model) => model.morphTo('imageable', { Post, User }),
}
}The parents declare morphMany (or morphOne for a single result). Add this to the relations of Post (and the same to User):
images: (model: Model) => model.morphMany(Image, 'imageable'),morphTo needs the map because JavaScript has no way to turn the string 'Post' back into a class. Eager loading a morphTo issues one query per distinct type. A row whose type is missing from the map loads as null.
const images = await Image.query().with('imageable').get()
images[0]!.getRelation('imageable') // => a Post or a User modelTo store a morph row, use the relation object. morphOne and morphMany have create(), createMany(), save() and saveMany(), which set the id column and the type column (from morphClass()) for you:
const post = (await Post.find(1))!
const images = post.relation('images') as MorphMany
await images.create({ url: 'cover.png' })
await images.createMany([{ url: 'a.png' }, { url: 'b.png' }])
await images.save(new Image({ url: 'c.png' }))Import MorphMany and MorphOne from @plinthjs/orm. Model.relation(name) returns the relation instance.
To change the stored type string, override morphClass() on the model.
Polymorphic many to many
morphToMany(related, name, relatedPivotKey, pivotTable = name + 's') relates a morphable model to a shared table through a pivot that also carries a type column. morphedByMany is the inverse, defined on the shared model.
await schema.create('tags', (table) => {
table.id()
table.string('name')
table.timestamps()
})
await schema.create('taggables', (table) => {
table.integer('tag_id')
table.integer('taggable_id')
table.string('taggable_type')
})
class Tag extends Model {
static override table = 'tags'
static override fillable = ['name']
static override relations = {
posts: (model: Model) => model.morphedByMany(Post, 'taggable', 'tag_id'),
}
}
class TaggedPost extends Model {
static override table = 'posts'
static override relations = {
tags: (model: Model) => model.morphToMany(Tag, 'taggable', 'tag_id'),
}
}The pivot defaults to taggables. Every pivot read, insert and delete is scoped to the model's morph type, so attach, detach, sync and toggle work as they do for a plain many to many relation.
Loading Relationships
Eager loading
with() accepts any number of relation names. It is available on Model.query() and on the builders returned by Model.where() and Model.newQuery():
const users = await User.query().with('posts', 'profile').get()
const ann = await User.where('name', 'Ann').with('posts').first()Model.query() is the relationship builder: it supports where, whereIn, whereNull, whereNotNull, with, the aggregate methods below, withTrashed(), onlyTrashed(), get(), first() and firstOrFail(). It hides soft deleted rows unless you ask for them. Model.where() is the active-record builder with the full fluent surface (ordering, limits, scopes, soft deletes). Both load relations with the same batched algorithm.
Nested relationships
Use dot notation for a relation of a relation. Each level costs one query:
const users = await User.query().with('posts.comments').get()
users[0]!.getRelation<Post[]>('posts')[0]!.getRelation<Comment[]>('comments')Constraining eager loads
Pass an object instead of a string to constrain a relation's query. The function receives the relation's builder:
const users = await User.query()
.with({ posts: (query) => query.where('published', true) })
.get()
// Constrain a nested level with its full path.
await User.query()
.with({ 'posts.comments': (query) => query.where('body', 'like', '%nice%') })
.get()You can mix strings and objects in one with() call, and the nested path with a constraint also loads the parent level.
Loading onto an existing model
load() takes the same specs and fills relations on a model you already have. It returns the model:
const user = (await User.find(1))!
await user.load('posts', 'profile')
await user.load({ posts: (query) => query.where('votes', '>', 4) })To load relations onto a list of models you already fetched, use the exported eagerLoad() helper. It is still one query per relation for the whole list:
import { eagerLoad } from '@plinthjs/orm'
const users = await User.all()
await eagerLoad(users, ['posts', 'profile'])Querying the relation
related(name) returns a query already constrained to this model. Add conditions and call get() or first():
const recent = await user.related('posts').where('votes', '>', 2).get()
const one = await user.related('posts').where('published', true).first()
await user.related('posts').with('comments').get() // eager load on the relation queryrelated() builds on the relationship query builder, so it supports where, whereIn, with and the aggregates, but not ordering or limits. It works for every relation type, including many to many, polymorphic many to many and through relations: those look up the pivot (or intermediate) rows first, when the query runs, and then constrain the related table to the ids found, so user.related('roles').where('name', 'admin').get() costs two queries.
To get the relation object itself (to insert or attach), use relation(name). It is covered below. Asking for an undefined name throws Relation [nope] is not defined on [User].
Relationship Aggregates
To count or summarize related rows without loading them, use the aggregate methods on Model.query(). The result is stored as an attribute on each model under a predictable name:
| Method | Attribute |
|---|---|
withCount('posts') | posts_count |
withSum('posts', 'votes') | posts_sum_votes |
withAvg('posts', 'votes') | posts_avg_votes |
withMin('posts', 'votes') | posts_min_votes |
withMax('posts', 'votes') | posts_max_votes |
const users = await User.query()
.withCount('posts')
.withSum('posts', 'votes')
.withAvg('posts', 'votes')
.get()
users[0]!.getAttribute('posts_count') // => 3
users[0]!.getAttribute('posts_sum_votes') // => 18
users[0]!.getAttribute('posts_avg_votes') // => 6Pass a constraint to count a subset. withCount takes a { relation: constraint } object; the others take the constraint as a last argument:
await User.query()
.withCount({ posts: (query) => query.where('published', true) })
.withMax('posts', 'votes', (query) => query.where('published', true))
.get()An empty relation yields 0 for counts and sums and null for averages, minimums and maximums. Aggregates work for every relation type, including many to many.
INFO
The aggregate methods exist on the relationship builder (Model.query()) only, not on the builders returned by Model.where().
Inserting and Updating Related Models
model.relation(name) returns the relation object, which has the methods for writing related data. Cast it to the concrete relation type to see them:
import type { BelongsTo, BelongsToMany, HasMany } from '@plinthjs/orm'Creating children
HasMany and HasOne set the foreign key for you:
const user = (await User.find(1))!
const posts = user.relation('posts') as HasMany
const post = await posts.create({ title: 'Hello' }) // new post with user_id = 1
await posts.createMany([{ title: 'One' }, { title: 'Two' }])
const existing = new Post({ title: 'Draft' })
await posts.save(existing) // sets user_id, then saves
await posts.saveMany([new Post({ title: 'A' }), new Post({ title: 'B' })])Belongs to
associate() points a child at an owner by copying the owner key into the foreign key, and records the owner as the loaded relation. It does not save, so call save() afterwards. dissociate() clears the foreign key.
const comment = (await Comment.first())!
const target = (await Post.find(2))!
;(comment.relation('post') as BelongsTo).associate(target)
await comment.save()
;(comment.relation('post') as BelongsTo).dissociate()
await comment.save() // post_id is now null (the column must be nullable)Pivot Tables
A BelongsToMany relation writes the pivot table directly.
const roles = user.relation('roles') as BelongsToMany
await roles.attach(1) // by id
await roles.attach(role) // or by model
await roles.attach([1, 2], { granted_by: 'root' }) // many ids, shared pivot columnsdetach() removes rows and returns how many it removed. Without arguments it detaches everything:
await roles.detach(2) // => 1
await roles.detach() // all roles for this usersync() makes the pivot match exactly the ids you give it, and tells you what changed. Pass false as the second argument to attach without detaching the others. To set pivot columns per id, pass a Map from id to pivot row. Rows that are already attached get their pivot columns updated when the values differ, and their ids are reported in updated:
const result = await roles.sync([1, 2])
result // => { attached: [2], detached: [], updated: [] }
await roles.sync(new Map([[3, { granted_by: 'ann' }]]), false)
await roles.sync(new Map([[3, { granted_by: 'bob' }]]), false)
// => { attached: [], detached: [], updated: [3] }A data source without an update() method (a custom one) replaces the changed pivot row instead.
toggle() attaches the ids that are missing and detaches the ones that are present:
await roles.toggle([2, 3]) // => { attached: [3], detached: [2] }All of these work on morph many to many relations as well, scoped to the morph type.
Pivot columns are not merged into the related models when you load the relation. To read them, query the pivot table with the database builder, for example db.table('role_user').where('user_id', 1).get().
Testing
Because relationships read through Model.dataSource (derived from Model.connection unless you set it), tests can use sqliteConnection() as on this page, or swap in the in-memory ArrayDataSource for fast tests that need no schema:
import { ArrayDataSource } from '@plinthjs/orm'
Model.dataSource = new ArrayDataSource({
users: [{ id: 1, name: 'Ann' }],
posts: [{ id: 1, user_id: 1, title: 'Hello' }],
})
const users = await User.query().with('posts').get()ArrayDataSource supports reads and the pivot writes above, but not the active-record persistence methods, which need Model.connection. For generating test data, see Factories.