Skip to content

Defining Models ​

A model is a typed object for one database table. You use it to query rows, create and update records, and load relationships, with autocomplete for every column name.

ts
import { defineModel } from '@holo-js/db'

export default defineModel('posts', {
  fillable: ['title', 'slug', 'body', 'status', 'user_id'],
})
ts
import Post from '../models/Post'

const post = await Post.findOrFail(1)
post.title
//   ^? string

const drafts = await Post.where('status', 'draft').latest().get()

Create a model ​

Generate a model with the CLI:

bash
npx holo make:model Post

This writes server/models/Post.ts for the posts table. Add companion files with flags:

bash
npx holo make:model Post --migration --factory --seeder --observer
FlagShortCreates
--migration-mA create_posts_table migration
--factory-fA PostFactory factory
--seeder-sA PostSeeder seeder
--observer-oA PostObserver observer, already wired into the model
--table <name>Uses a custom table name instead of the inferred one

Nested names create nested folders: npx holo make:model billing/Invoice writes server/models/billing/Invoice.ts.

When you run make:model without flags in a terminal, Holo asks which companion files you want.

WARNING

The generated model starts with fillable: [], which blocks every column from create() and update(). List the columns you want to write before you use it. See mass assignment.

Where the types come from ​

You don't declare columns in the model. Holo reads them from your database after your migrations run:

  1. You write a migration that creates or changes the posts table.
  2. You run npx holo migrate. npx holo migrate:rollback, npx holo migrate:fresh, and npx holo build do the same step.
  3. Holo reads the database and regenerates .holo-js/generated/schema.generated.ts with every table's columns. Don't edit this file.
  4. defineModel('posts') picks up those column types.
  5. The model's built-in casts set the type of the columns the database can't describe, such as JSON stored in a SQLite text column.

After a migration, every model method knows your columns:

ts
await Post.where('status', 'published').get()
await Post.orderBy('published_at', 'desc').first()
await Post.pluck('title')
//    ^? Promise<string[]>

await Post.where('titel', 'Hello')
//               ^ TypeScript error: 'titel' is not a column of posts

Records are typed too. A text().nullable() column reads as string | null, a timestamp() as Date, and create() requires every column that has no default. A column with a 'json', 'boolean', 'number', 'string', 'date', 'datetime', 'timestamp', or 'vector' cast takes the cast's type instead, both when you read it and when you write it. Models you reach by name, such as belongsTo('User'), and the user from auth.user() get the same types.

TIP

If autocomplete shows stale columns, run npx holo migrate again. On a fresh clone of a project whose database already exists, npx holo dev, npx holo migrate or npx holo build writes the full types. A model on the default connection whose table isn't in the generated schema throws Model "posts" is not present in the Generated schema at runtime.

Conventions ​

Model names ​

Holo infers the model name from the table name by singularizing it and converting it to PascalCase:

TableModel name
usersUser
blog_postsBlogPost
peoplePerson

The name appears in error messages and is how string relation targets like belongsTo('User', ...) find the model. Override it with name:

ts
import { defineModel } from '@holo-js/db'

export default defineModel('people', {
  name: 'Member',
})

Primary keys ​

Holo uses the column your migration marked as the primary key, usually table.id(). Set primaryKey only when you want a different column:

ts
export default defineModel('countries', {
  primaryKey: 'code',
})

Models don't support composite primary keys, as in Laravel. A model on a table whose primary key has several columns throws SchemaError when an operation needs its key, such as find(), create() or save(), unless you set primaryKey to one of them. Use such a table as a belongsToMany pivot instead. See primary(columns).

An id() key is typed number, so the model reads it as it reads integer() and bigInteger() columns. A key beyond Number.MAX_SAFE_INTEGER throws a HydrationError on every database. If a table's keys can pass that range, use UUID, ULID, or Snowflake keys, which are read as strings.

Timestamps ​

If the table has created_at and updated_at columns, Holo fills them on create and refreshes updated_at on every save. Add both columns in a migration with table.timestamps().

Turn this off, or rename the columns:

ts
export default defineModel('audit_logs', {
  timestamps: false,
})

export default defineModel('articles', {
  createdAtColumn: 'published_on',
  updatedAtColumn: 'edited_on',
})

Connections ​

Models use the default connection. Point a model at another named connection with connectionName:

ts
export default defineModel('events', {
  connectionName: 'analytics',
})

The generated schema covers only the default connection, so a model on another connection is untyped, as in Laravel: its attributes are unknown, and casts, fillable and guarded work as usual. See Point a model at a connection for what it does at runtime, and multiple connections for configuring named connections.

Mass assignment ​

create(), update(), make(), fill(), set(), and property assignment only accept columns you allow. Assigning any other column throws a SecurityError right away, so unexpected request fields never reach the database. A model without fillable or guarded allows no columns.

A JSON path such as settings->theme follows the rules of its column, settings.

List allowed columns with fillable:

ts
export default defineModel('users', {
  fillable: ['name', 'email', 'password'],
})

Or block specific columns with guarded, and allow the rest:

ts
export default defineModel('users', {
  guarded: ['is_admin'],
})
SettingWhat can be written
No fillable or guardedNothing
fillable: ['name', 'email']Only name and email
fillable: []Nothing
fillable: ['*']Every column except guarded ones
guarded: ['is_admin']Every column except is_admin
guarded: []Every column except the primary key and timestamps
guarded: ['*']Nothing

The primary key and the created_at and updated_at columns are guarded unless you name them in fillable. fillable: ['*'] and guarded lists don't open them. Holo still fills in generated IDs and timestamps itself.

To write a protected column from trusted code, see writing guarded columns.

Soft deletes ​

Soft-deleted rows stay in the table with a deleted_at timestamp and are hidden from normal queries. Add the column in a migration with table.softDeletes(), then enable it on the model:

ts
import { defineModel } from '@holo-js/db'

export default defineModel('posts', {
  softDeletes: true,
})

Use deletedAtColumn if the column has a different name. If the column is missing, the model throws a SchemaError the first time you use it.

See querying soft-deleted models and deleting and restoring.

UUID, ULID, and Snowflake keys ​

Give the model a unique ID trait and Holo generates the key when you create a record. To pass a key yourself, add the key column to fillable; Holo keeps the key you pass.

ts
import { defineModel, HasUuids } from '@holo-js/db'

export default defineModel('orders', {
  fillable: ['total'],
  traits: [HasUuids()],
})
ts
const order = await Order.create({ total: 4999 })
order.id
// '01920c4e-7b1a-7c3e-9f00-2d5a1b7c9e10'
TraitGeneratesMigration column
HasUuids()UUID v7table.uuid('id').primaryKey()
HasUlids()ULIDtable.ulid('id').primaryKey()
HasSnowflakes()Snowflake ID stringtable.snowflake('id').primaryKey()
HasUniqueIds()Your own generatorAny string column

Generate IDs for a column other than the primary key with columns. The column must be the primary key or unique:

ts
import { defineModel, HasUlids } from '@holo-js/db'

export default defineModel('invoices', {
  traits: [HasUlids({ columns: ['public_id'] })],
})

Use HasUniqueIds with newUniqueId for a custom format:

ts
import { randomUUID } from 'node:crypto'
import { defineModel, HasUniqueIds } from '@holo-js/db'

export default defineModel('tickets', {
  traits: [HasUniqueIds({ columns: ['reference'] })],
  newUniqueId: () => `TCK-${randomUUID().slice(0, 8)}`,
})

A model can use only one unique ID trait.

Default attribute values ​

pendingAttributes sets starting values for new records. Values you pass to create() or make() win.

ts
export default defineModel('posts', {
  fillable: ['title', 'body', 'status'],
  pendingAttributes: {
    status: 'draft',
  },
})
ts
const post = await Post.create({ title: 'Hello', body: '...' })
post.status
// 'draft'

Touching parent timestamps ​

touches updates the parent's updated_at whenever this model is created, saved, deleted, or restored. It's useful when a list sorts by "last activity".

ts
import { belongsTo, defineModel } from '@holo-js/db'

export default defineModel('comments', {
  relations: {
    post: belongsTo('Post', { foreignKey: 'post_id' }),
  },
  touches: ['post'],
})

Only belongsTo and morphTo relations can be touched.

Pruning old records ​

Define prunable to describe which rows are safe to delete, then run npx holo prune:

ts
import { defineModel } from '@holo-js/db'

export default defineModel('login_attempts', {
  prunable: query => query.where('created_at', '<', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)),
})
bash
npx holo prune
npx holo prune LoginAttempt

Without arguments, holo prune prunes every model that defines prunable. You can also call await LoginAttempt.prune(), which returns the number of deleted rows.

By default Holo loads and deletes each row so model events fire, and permanently deletes soft-deleted models. Set massPrunable: true to delete with a single query instead. That's faster, but skips events.

Strict mode ​

Three options make the model throw instead of silently doing extra or wrong work. They're most useful in development and tests.

ts
export default defineModel('posts', {
  preventLazyLoading: true,
  preventAccessingMissingAttributes: true,
})
  • preventLazyLoading throws when you access a relationship you didn't eager load.
  • preventAccessingMissingAttributes throws when you read a column that wasn't selected, instead of returning undefined.
  • automaticEagerLoading loads a relationship for the whole result set the first time you access it on one record.

You can also toggle them at runtime: Post.preventLazyLoading(), Post.preventAccessingMissingAttributes(), Post.automaticallyEagerLoadRelationships(). Each takes an optional boolean.

Model options reference ​

OptionTypeDescription
namestringModel name. Defaults to the singular PascalCase table name.
primaryKeycolumnPrimary key column. Defaults to the migration's primary key.
connectionNamestringNamed database connection.
fillablecolumn[]Columns allowed in mass assignment. '*' allows all.
guardedcolumn[]Columns blocked from mass assignment. '*' blocks all.
timestampsbooleanFill created_at and updated_at when those columns exist. Default true.
createdAtColumncolumnCustom created-at column.
updatedAtColumncolumnCustom updated-at column.
softDeletesbooleanEnable soft deletes. Default false.
deletedAtColumncolumnCustom deleted-at column. Default deleted_at.
pendingAttributesobjectDefault values for new records.
traitsarrayUnique ID trait: HasUuids(), HasUlids(), HasSnowflakes(), HasUniqueIds().
uniqueIdscolumn[]Columns that get generated IDs. Overrides the trait's columns.
newUniqueId() => stringCustom ID generator.
scopesobjectLocal scopes.
globalScopesobjectGlobal scopes.
relationsobjectRelationships.
withstring[]Relationships to always eager load.
touchesstring[]Parent relations whose updated_at to refresh.
castsobjectAttribute casts.
accessorsobjectAccessors.
mutatorsobjectMutators.
hiddenstring[]Attributes left out of JSON. See serialization.
visiblestring[]Only these attributes appear in JSON.
appendedstring[]Accessors added to JSON.
serializeDate(date: Date) => unknownHow dates are written to JSON.
collectionfunctionCustom collection factory.
eventsobjectInline model events.
observersarrayObservers.
prunable(query) => queryRows that prune() deletes.
massPrunablebooleanPrune with one query, without events.
replicationExcludesstring[]Columns that replicate() never copies.
morphClassstringType value stored in polymorphic columns. Defaults to the model name.
preventLazyLoadingbooleanThrow on lazy relationship access.
preventAccessingMissingAttributesbooleanThrow when reading unselected columns.
automaticEagerLoadingbooleanLoad a relationship for the whole result set on first access.

Next steps ​

Released under the MIT License.