Database

Entities

Define database entities with @Entity, @PrimaryKey and @Column, add timestamps, soft deletes, relations and indexes, and query them with BaseModel.

8 min readUpdated DocumentationEdit this page
On this page12

An entity is a TypeScript class that describes one table. This page covers every entity decorator in @axiljs/orm, what each one records, and the Active Record API you get when the entity extends BaseModel.

TypeScript
TS
1import { BaseModel, Entity, PrimaryKey, Column, CreatedAt, UpdatedAt } from '@axiljs/orm'
2
3@Entity('users')
4export class User extends BaseModel {
5  @PrimaryKey()
6  id!: number
7
8  @Column({ type: 'string', length: 255 })
9  name!: string
10
11  @Column({ type: 'string', unique: true })
12  email!: string
13
14  @Column({ type: 'boolean', name: 'is_active', default: true })
15  isActive!: boolean
16
17  @CreatedAt()
18  createdAt!: Date
19
20  @UpdatedAt()
21  updatedAt!: Date | null
22}

The decorators use the legacy TypeScript decorator signature, so enable them in tsconfig.json:

JSON
JSON
1{
2  "compilerOptions": {
3    "experimentalDecorators": true
4  }
5}

axil generate entity product scaffolds src/modules/product/entities/product.entity.ts with this shape. See CLI project commands.

Note

Decorators only record metadata for the ORM. They do not create tables, columns, constraints or indexes, and there is no schema sync. Create the table in a migration so the database matches the entity.

@Entity(tableName?)

Marks the class as an entity and sets its table. Without an argument the table name is the class name lower-cased plus s (User becomes users). There is no real pluralisation (Category becomes categorys), so pass the name explicitly.

@PrimaryKey(options?)

OptionTypeDefaultDescription
type'integer' | 'bigint' | 'uuid' | 'string''integer'Key type
generatedbooleantrueThe database generates the value
autoIncrementbooleantrueAlias for generated, used when generated is not set
namestringproperty nameColumn name
TypeScript
TS
1@Entity('api_keys')
2export class ApiKey extends BaseModel {
3  @PrimaryKey({ type: 'uuid', generated: false })
4  id!: string
5
6  @Column()
7  label!: string
8}
9
10await ApiKey.create({ id: crypto.randomUUID(), label: 'CI' })

Caller-supplied keys such as UUIDs are kept on insert. Only an empty key is left for the database to generate.

@Column(options?)

OptionTypeDefaultDescription
typeColumnType'string'Logical type, listed below
namestringproperty nameColumn name in the table
nullablebooleanfalseColumn accepts NULL
uniquebooleanfalseColumn is unique
defaultunknownnoneDefault value
lengthnumbernoneLength for strings
precisionnumbernonePrecision for decimals
scalenumbernoneScale for decimals

Column types: string, number, integer, bigint, float, decimal, boolean, date, datetime, timestamp, text, json, jsonb, uuid, enum.

BaseModel maps between property and column names in both directions: isActive is written to and read from is_active above. BaseRepository does not map names, see Repositories.

Timestamps

DecoratorColumnDefinition
@CreatedAt()created_attimestamp, not null, default CURRENT_TIMESTAMP
@UpdatedAt()updated_attimestamp, nullable
@DeletedAt()deleted_attimestamp, nullable, turns on soft deletes

The column names are fixed. The ORM does not fill updated_at for you; set it when you change a row:

TypeScript
TS
user.name = 'Tariq Mehmood'
user.updatedAt = new Date()
await user.save()

created_at is filled by the column default when the insert leaves it out, which User.create({...}) does. save() on a new instance writes every decorated column, so set createdAt before saving a new User(), or use create().

Soft deletes with @DeletedAt()

Adding @DeletedAt() makes the entity soft-deletable, for both BaseModel and BaseRepository:

  • delete() sets deleted_at to the current time instead of removing the row.
  • Reads skip soft-deleted rows unless you ask for them with withTrashed or onlyTrashed.
  • restore() clears deleted_at; forceDelete() removes the row for good.
TypeScript
TS
1@Entity('posts')
2export class Post extends BaseModel {
3  @PrimaryKey() id!: number
4  @Column() title!: string
5  @DeletedAt() deletedAt!: Date | null
6}
7
8const post = await Post.findOrFail(1)
9await post.delete()               // UPDATE posts SET deleted_at = ...
10post.trashed()                    // true
11await Post.find(1)                // null
12await Post.find(1, { withTrashed: true })
13await post.restore()
14await post.forceDelete()          // DELETE FROM posts ...

Relations

DecoratorMeaning
@HasOne(() => Target, options?)The other table holds a key pointing at this row
@HasMany(() => Target, options?)Many rows in the other table point at this row
@BelongsTo(() => Target, options?)This table holds a key pointing at the other row
@ManyToMany(() => Target, options?)Linked through a pivot table

Options are foreignKey, pivotTable and relatedKey (pivot tables only). eager is accepted but only recorded; relations load when you ask with with() or load().

TypeScript
TS
1import { HasMany, BelongsTo } from '@axiljs/orm'
2
3@Entity('authors')
4export class Author extends BaseModel {
5  @PrimaryKey() id!: number
6  @Column() name!: string
7  @HasMany(() => Book) books?: Book[]
8}
9
10@Entity('books')
11export class Book extends BaseModel {
12  @PrimaryKey() id!: number
13  @Column({ name: 'author_id', type: 'integer' }) authorId!: number
14  @BelongsTo(() => Author) author?: Author
15}
16
17const authors = await Author.all({ with: ['books'] })

Default key names, nested paths such as 'books.reviews', and many-to-many pivots are covered in Relations.

Indexes

@Index(options?) on a property and @CompositeIndex(columns, options?) on the class record index metadata. Both take name and unique (default false). Default names are idx_<property> and idx_<col1>_<col2>.

TypeScript
TS
1import { Index, CompositeIndex } from '@axiljs/orm'
2
3@Entity('orders')
4@CompositeIndex(['customer_id', 'status'], { name: 'idx_orders_customer_status' })
5export class Order extends BaseModel {
6  @PrimaryKey() id!: number
7
8  @Index({ unique: true })
9  @Column()
10  reference!: string
11}

Like the other decorators, these do not create indexes. Add them in a migration with table.index() or table.uniqueIndex(), see Migrations.

Active Record with BaseModel

When an entity extends BaseModel, its static and instance methods run queries against one shared driver. Register it once at startup:

TypeScript
TS
1import { BaseModel, createConnection } from '@axiljs/orm'
2
3const db = await createConnection({ driver: 'postgres', url: process.env.DATABASE_URL })
4BaseModel.setDriver(db.getDriver(), 'postgres')

The second argument must match the database ('postgres', 'mysql' or 'sqlite'), because it selects placeholders and RETURNING support. Without setDriver(), every call throws No driver. Call BaseModel.setDriver() first.

Static methods

MethodReturnsDescription
all(options?)Promise<User[]>Every row as instances
find(id, options?)Promise<User | null>Find by primary key
findOrFail(id)Promise<User>Find or throw User id=1 not found.
create(data)Promise<User>Insert and return the stored row as an instance
where(column, operator, value)query builderStart a filtered query. Operators: =, !=, >, <, >=, <=, LIKE
query()query builderFull query builder scoped to the table
with(...relations)query builderQuery with eager-loaded relations
withTrashed(), onlyTrashed()query builderInclude or limit to soft-deleted rows
updateWhere(conditions, data)Promise<number>Update matching rows, returns the count
deleteWhere(conditions)Promise<number>Delete (or soft-delete) matching rows
count()Promise<number>Count rows
paginate(page, perPage = 15){ data, total, page, perPage, lastPage }One page of instances

options for all() and find() is { with?: string[], withTrashed?: boolean, onlyTrashed?: boolean }.

TypeScript
TS
1const user = await User.create({ name: 'Tariq', email: 'tariq@axiljs.dev' })
2
3const admins = await User.where('role', '=', 'admin')
4  .orderBy('created_at', 'DESC')
5  .limit(10)
6  .get()
7
8const page = await User.paginate(2, 20)

Note

where(), query() and the other builder methods return plain rows keyed by column name, not User instances. Use all(), find() and paginate() when you need instances. The builder methods are listed in Query Builder.

Instance methods

MethodDescription
save()INSERT for a new instance, otherwise UPDATE of only the changed columns
delete()Delete, or soft-delete for @DeletedAt entities
forceDelete()Always DELETE
restore()Clear deleted_at (@DeletedAt entities only)
trashed()true when soft-deleted
refresh()Reload the row from the database
load(...relations)Eager-load relations onto this instance
isDirty(column?)true when a column, or any column, changed since load or last save
isNew()true until the instance is first saved
toJSON()Column-keyed object, including loaded relations
TypeScript
TS
1const user = new User()
2user.name = 'Ann'
3user.email = 'ann@axiljs.dev'
4user.isActive = true
5user.createdAt = new Date()
6await user.save()                 // INSERT, sets user.id
7
8user.name = 'Ann Lee'
9user.isDirty('name')              // true
10await user.save()                 // UPDATE users SET name = ... WHERE id = ...
11
12const author = await Author.findOrFail(1)
13await author.load('books')
14res.success(author.toJSON())      // { id, name, books: [...] }

Reading metadata

getEntityMetadata(Class) returns the recorded EntityMeta (tableName, primaryKey, columns, relations, indexes, softDelete), and getAllEntities() returns every registered entity. Tools such as ORM Studio and your own code generators can build on these.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY