约定
使用 ID 作为主键
默认情况下,IBest-ORM 会使用 id 作为表的主键。你可以通过 @PrimaryKey() 装饰器将其它字段设为主键。
ts
import { Table, Column, PrimaryKey, ColumnType } from '@ibestservices/ibest-orm';
@Table()
class User {
@PrimaryKey()
uid?: number;
@Column()
name?: string;
}表名
您可以通过 @Table 装饰器参数来指定表名:
ts
@Table({ name: 'users' })
class User {}
// 或简写
@Table('users')
class User {}如果未指定,则使用类名的蛇形命名作为默认表名:
ts
@Table()
class User {} // 表名: user
@Table()
class UserProfile {} // 表名: user_profile临时指定表名
您可以使用 table() 方法临时指定表名:
ts
const users = orm.table('users').where({ age: 18 }).find();列名
您可以通过 @Column 装饰器的 name 参数来指定列名:
ts
@Table()
class User {
@PrimaryKey()
id?: number;
@Column()
userName?: string; // 列名: user_name(自动蛇形命名)
@Column({ name: 'user_id', type: ColumnType.INTEGER })
userId?: number; // 列名: user_id(显式指定)
}如果未指定,则使用属性名的蛇形命名作为默认列名:
ts
@Table()
class User {
@PrimaryKey()
id?: number; // 列名: id
@Column()
name?: string; // 列名: name
@Column()
createdAt?: string; // 列名: created_at
}字段类型
使用 ColumnType 指定字段类型:
ts
import { ColumnType } from '@ibestservices/ibest-orm';
@Table()
class User {
@PrimaryKey()
id?: number;
@Column({ type: ColumnType.TEXT })
name?: string;
@Column({ type: ColumnType.INTEGER })
age?: number;
@Column({ type: ColumnType.REAL })
balance?: number;
@Column({ type: ColumnType.BLOB })
avatar?: Uint8Array;
}自动时间戳
使用 @CreatedAt 和 @UpdatedAt 装饰器自动管理时间戳:
ts
import { CreatedAt, UpdatedAt } from '@ibestservices/ibest-orm';
@Table()
class User {
@PrimaryKey()
id?: number;
@Column()
name?: string;
@CreatedAt()
createdAt?: string; // 插入时自动设置
@UpdatedAt()
updatedAt?: string; // 插入和更新时自动设置
}软删除
使用 @SoftDelete 装饰器启用软删除:
ts
import { SoftDelete } from '@ibestservices/ibest-orm';
@Table()
class Article {
@PrimaryKey()
id?: number;
@Column()
title?: string;
@SoftDelete()
deletedAt?: string; // 删除时设置时间戳,而非真正删除
}非空约束
使用 @NotNull 装饰器标记非空字段:
ts
import { NotNull } from '@ibestservices/ibest-orm';
@Table()
class User {
@PrimaryKey()
id?: number;
@NotNull()
@Column()
name!: string; // 非空字段
}