定义实体
实体就是简单的 JavaScript 对象(即所谓的 POJO),没有任何限制,也无需继承基类。使用实体构造函数同样可行 —— 对于受管实体(从数据库加载的)它们永远不会被执行。每个实体都必须有主键。
实体可以通过两种方式定义:
defineEntity辅助函数 —— 以编程方式定义实体,具备完整的 TypeScript 类型推断。你可以配合类使用(推荐),也可以不配合类使用。更多内容请阅读defineEntity一节。- 装饰器类 —— 实体的属性以及每个属性都通过装饰器提供。你在类上使用
@Entity()装饰器。实体属性要么用@Property装饰器修饰,要么用引用装饰器之一修饰:@ManyToOne、@OneToMany、@OneToOne与@ManyToMany。完整内容请查阅装饰器参考。
此外,从装饰器提取元数据的方式由 MetadataProvider 控制。三种主要的元数据提供者是:
MetadataProvider—— 默认提供者,只要求显式提供类型。ReflectMetadataProvider—— 使用reflect-metadata读取属性类型。更快但更简单也更冗长。TsMorphMetadataProvider—— 使用ts-morph从 TypeScript 编译 API 读取类型信息。更重(需要把完整的 TS 作为依赖),但允许 DRY 的实体定义方式。借助ts-morph,你能够提取代码中定义的原始类型,包括接口名以及属性的可选性。
关于它们的更多内容请阅读元数据提供者一节。关于使用装饰器(包括 v7 中新的 ES 规范装饰器)的完整指南,请参见使用装饰器指南。关于基于 glob 的实体发现,请参见基于文件夹的发现。
MikroORM 当前的装饰器集合是为配合
tsc使用而设计的。使用babel与swc同样可行,但需要一些额外配置。更多内容请阅读这里。关于webpack的说明,请阅读部署一节。
ts-morph仅与tsc方式兼容。
下面是 Book 实体的示例定义。你可以切换标签页查看不同方式的差异:
import { defineEntity, p } from '@mikro-orm/core';
const BookSchema = defineEntity({
name: 'Book',
extends: CustomBaseEntity,
properties: {
title: p.string(),
author: () => p.manyToOne(Author),
publisher: () => p.manyToOne(Publisher)
.ref()
.nullable(),
tags: () => p.manyToMany(BookTag)
.fixedOrder(),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);import { type InferEntity, defineEntity, p } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
extends: CustomBaseEntity,
properties: {
title: p.string(),
author: () => p.manyToOne(Author),
publisher: () => p.manyToOne(Publisher)
.ref()
.nullable(),
tags: () => p.manyToMany(BookTag)
.fixedOrder(),
},
});
export type IBook = InferEntity<typeof Book>;@Entity()
export class Book extends CustomBaseEntity {
@Property()
title!: string;
@ManyToOne(() => Author)
author!: Author;
@ManyToOne(() => Publisher, { ref: true, nullable: true })
publisher?: Ref<Publisher>;
@ManyToMany(() => BookTag, { fixedOrder: true })
tags = new Collection<BookTag>(this);
}@Entity()
export class Book extends CustomBaseEntity {
@Property()
title!: string;
@ManyToOne()
author!: Author;
@ManyToOne()
publisher?: Ref<Publisher>;
@ManyToMany({ fixedOrder: true })
tags = new Collection<BookTag>(this);
}在
Ref属性定义中加入{ ref: true }会把该引用包装起来,从而提供.load、.unwrap等辅助方法的访问能力,这在加载数据以及在使用处改变引用类型时很有帮助。
如果你想要一个纯类型的替代方案 —— 运行时值仍保持为普通实体(没有
Reference包装器,没有.$间接层),但依然限制到Loaded<>收窄之后才能访问 —— 请把属性声明为LazyRef<T>。参见类型安全关系 →LazyRef<T>。
下面是另一个示例 —— Book 中引用到的 Author 实体,这次是为 mongo 定义的:
import { defineEntity, p } from '@mikro-orm/core';
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
_id: p.type(ObjectId).primary(),
id: p.string().serializedPrimaryKey(),
createdAt: p.datetime().onCreate(() => new Date()),
updatedAt: p.datetime()
.onCreate(() => new Date())
.onUpdate(() => new Date()),
name: p.string(),
email: p.string(),
age: p.integer().nullable(),
termsAccepted: p.boolean(),
identities: p.array().nullable(),
born: p.date().nullable(),
books: () => p.oneToMany(Book).mappedBy(book => book.author),
friends: () => p.manyToMany(Author),
favouriteBook: () => p.manyToOne(Book).nullable(),
version: p.integer().version(),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);import { type InferEntity, defineEntity, p } from '@mikro-orm/core';
export const Author = defineEntity({
name: 'Author',
properties: {
_id: p.type(ObjectId).primary(),
id: p.string().serializedPrimaryKey(),
createdAt: p.datetime().onCreate(() => new Date()),
updatedAt: p.datetime()
.onCreate(() => new Date())
.onUpdate(() => new Date()),
name: p.string(),
email: p.string(),
age: p.integer().nullable(),
termsAccepted: p.boolean(),
identities: p.array().nullable(),
born: p.date().nullable(),
books: () => p.oneToMany(Book).mappedBy(book => book.author),
friends: () => p.manyToMany(Author),
favouriteBook: () => p.manyToOne(Book).nullable(),
version: p.integer().version(),
},
});
export type IAuthor = InferEntity<typeof Author>;@Entity()
export class Author {
@PrimaryKey()
_id!: ObjectId;
@SerializedPrimaryKey()
id!: string;
@Property()
createdAt = new Date();
@Property({ onUpdate: () => new Date() })
updatedAt = new Date();
@Property()
name!: string;
@Property()
email!: string;
@Property({ nullable: true })
age?: number;
@Property()
termsAccepted: boolean = false;
@Property({ nullable: true })
identities?: string[];
@Property({ nullable: true })
born?: string;
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
@ManyToMany(() => Author)
friends = new Collection<Author>(this);
@ManyToOne(() => Book, { nullable: true })
favouriteBook?: Book;
@Property({ version: true })
version!: number;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
}@Entity()
export class Author {
@PrimaryKey()
_id!: ObjectId;
@SerializedPrimaryKey()
id!: string;
@Property()
createdAt = new Date();
@Property({ onUpdate: () => new Date() })
updatedAt = new Date();
@Property()
name!: string;
@Property()
email!: string;
@Property()
age?: number;
@Property()
termsAccepted = false;
@Property()
identities?: string[];
@Property()
born?: string;
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
@ManyToMany()
friends = new Collection<Author>(this);
@ManyToOne()
favouriteBook?: Book;
@Property({ version: true })
version!: number;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
}关于关系建模的更多信息可以在关系建模页面找到。
原生 JavaScript 用法的示例请查看这里。
可选属性
使用默认的 reflect-metadata 提供者时,你需要把每个可选属性标记为 nullable: true。使用 ts-morph 时,如果你把属性定义为可选(用 ? 标记),它会被自动视为可空属性(主要针对 SQL schema 生成器)。
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
favouriteBook: p.manyToOne(Book).nullable(),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
favouriteBook: p.manyToOne(Book).nullable(),
},
});
export type ISomeEntity = InferEntity<typeof SomeEntity>;@ManyToOne(() => Book, { nullable: true })
favouriteBook?: Book;@ManyToOne()
favouriteBook?: Book;要让可空字段在 em.create() 这类方法中变成必填(即你不能省略该属性),请使用 RequiredNullable 类型。这类属性必须在 em.create() 方法中显式提供,但可以接受 null 值。
const BookSchema = defineEntity({
name: 'Book',
properties: {
title: p.string().$type<RequiredNullable<string>>(),
},
});
em.create(Book, { title: "Alice in Wonderland" }); // ok
em.create(Book, { title: null }); // ok
em.create(Book, {}); // 编译错误:缺少 titleconst Book = defineEntity({
name: 'Book',
properties: {
title: p.string().$type<RequiredNullable<string>>(),
},
});
em.create(Book, { title: "Alice in Wonderland" }); // ok
em.create(Book, { title: null }); // ok
em.create(Book, {}); // 编译错误:缺少 titleclass Book {
@Property()
title!: RequiredNullable<string>;
}
em.create(Book, { title: "Alice in Wonderland" }); // ok
em.create(Book, { title: null }); // ok
em.create(Book, {}); // 编译错误:缺少 titleclass Book {
@Property()
title!: RequiredNullable<string>;
}
em.create(Book, { title: "Alice in Wonderland" }); // ok
em.create(Book, { title: null }); // ok
em.create(Book, {}); // 编译错误:缺少 title默认值
你可以通过 2 种方式设置属性的默认值:
- 使用属性初始化器。只要你没有使用诸如
now()这样的原生数据库函数,就应当优先采用这种方式。使用这种方式时,你的实体在真正被持久化到数据库之前就已经拥有默认值(例如当你通过new Author()或em.create(Author, { ... })实例化新实体时)。
只有当你拥有真正的实体类(而非接口)时这才可行。如果你不配合类使用
defineEntity,可以用onCreate选项来设置默认值。
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
foo: p.integer().onCreate(() => 1),
bar: p.string().onCreate(() => 'abc'),
baz: p.datetime().onCreate(() => new Date()),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
foo: p.integer().onCreate(() => 1),
bar: p.string().onCreate(() => 'abc'),
baz: p.datetime().onCreate(() => new Date()),
},
});@Property()
foo: number & Opt = 1;
@Property()
bar: string & Opt = 'abc';
@Property()
baz: Date & Opt = new Date();@Property()
foo: number & Opt = 1;
@Property()
bar: string & Opt = 'abc';
@Property()
baz: Date & Opt = new Date();- 使用
@Property装饰器的default参数。这样实际的默认值将由数据库提供,并在实体被持久化之后(flush 之后)自动映射到实体属性上。要使用now()这类 SQL 函数,请使用defaultRaw。
SQL 函数请使用
defaultRaw,因为带字符串值的default会被自动加引号。
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
foo: p.integer().default(1),
bar: p.string().default('abc'),
baz: p.datetime().defaultRaw('now'),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
foo: p.integer().default(1),
bar: p.string().default('abc'),
baz: p.datetime().defaultRaw('now'),
},
});@Property({ default: 1 })
foo!: number & Opt;
@Property({ default: 'abc' })
bar!: string & Opt;
@Property({ defaultRaw: 'now' })
baz!: Date & Opt;@Property({ default: 1 })
foo!: number & Opt;
@Property({ default: 'abc' })
bar!: string & Opt;
@Property({ defaultRaw: 'now' })
baz!: Date & Opt;注意,Opt 类型用于与属性类型交叉,从而在类型层面告诉 ORM:该属性在输入类型中(例如 em.create())应被视为可选,但在受管实体中(例如 EntityDTO 类型)会始终存在。
枚举
要定义枚举属性,请使用 @Enum() 装饰器。枚举既可以是数值也可以是字符串值。
为了让 schema 生成器在字符串枚举的情况下正常工作,你需要把枚举定义在与使用处相同的文件中,这样它的值才能被自动发现。如果你想把枚举定义在另一个文件里,就应当在使用的位置把它重新导出。
你也可以通过 @Enum(() => UserRole) 在装饰器中提供对枚举实现的引用,或通过 @Enum({ items: UserRole }) 直接传入枚举对象 —— 只有当枚举声明在使用它的类之后时,才需要回调形式。
你也可以通过
items: string[]属性手动设置枚举项。
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
// 字符串枚举
role: p.enum(['admin', 'user']),
// 数值枚举
status: p.enum(() => UserStatus),
// 定义在本文件之外的字符串枚举
outside: p.enum(() => OutsideEnum),
// 定义在本文件之外的字符串枚举,可以为 null
outsideNullable: p.enum(() => OutsideNullableEnum).nullable(),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
// 字符串枚举
role: p.enum(['admin', 'user']),
// 数值枚举
status: p.enum(() => UserStatus),
// 定义在本文件之外的字符串枚举
outside: p.enum(() => OutsideEnum),
// 定义在本文件之外的字符串枚举,可以为 null
outsideNullable: p.enum(() => OutsideNullableEnum).nullable(),
},
});import { OutsideEnum } from './OutsideEnum.ts';
@Entity()
export class User {
@Enum(() => UserRole)
role!: UserRole; // 字符串枚举
@Enum(() => UserStatus)
status!: UserStatus; // 数值/常量枚举
@Enum(() => OutsideEnum)
outside!: OutsideEnum; // 定义在本文件之外的字符串枚举
@Enum({ items: () => OutsideNullableEnum, nullable: true })
outsideNullable?: OutsideNullableEnum; // 定义在本文件之外的字符串枚举,可以为 null
}
export enum UserRole {
ADMIN = 'admin',
MODERATOR = 'moderator',
USER = 'user',
}
export const enum UserStatus {
DISABLED,
ACTIVE,
}
// 或者你可以重新导出 OutsideEnum
// export { OutsideEnum } from './OutsideEnum.ts';import { OutsideEnum } from './OutsideEnum.ts';
@Entity()
export class User {
@Enum(() => UserRole)
role!: UserRole; // 字符串枚举
@Enum(() => UserStatus)
status!: UserStatus; // 数值枚举
@Enum(() => OutsideEnum)
outside!: OutsideEnum; // 定义在本文件之外的字符串枚举
@Enum({ items: () => OutsideNullableEnum })
outsideNullable?: OutsideNullableEnum; // 定义在本文件之外的字符串枚举,可以为 null
}
export enum UserRole {
ADMIN = 'admin',
MODERATOR = 'moderator',
USER = 'user',
}
export const enum UserStatus {
DISABLED,
ACTIVE,
}
// 或者你可以重新导出 OutsideEnum
// export { OutsideEnum } from './OutsideEnum.ts';PostgreSQL 原生枚举
默认情况下,PostgreSQL 驱动把枚举表示为带检查约束的文本列。从 v6 起,你可以通过设置 nativeEnumName 选项来启用原生枚举。
export enum UserRole {
ADMIN = 'admin',
MODERATOR = 'moderator',
USER = 'user',
}
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
role: p.enum(() => UserRole).nativeEnumName('user_role'),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);export enum UserRole {
ADMIN = 'admin',
MODERATOR = 'moderator',
USER = 'user',
}
export const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
role: p.enum(() => UserRole).nativeEnumName('user_role'),
},
});@Entity()
export class User {
@Enum({ items: () => UserRole, nativeEnumName: 'user_role' })
role!: UserRole;
}
export enum UserRole {
ADMIN = 'admin',
MODERATOR = 'moderator',
USER = 'user',
}@Entity()
export class User {
@Enum({ items: () => UserRole, nativeEnumName: 'user_role' })
role!: UserRole;
}
export enum UserRole {
ADMIN = 'admin',
MODERATOR = 'moderator',
USER = 'user',
}枚举数组
你也可以为枚举使用值数组,此时会自动使用 EnumArrayType 类型,它会在 flush 时校验其中的元素。
enum Role {
User = 'user',
Admin = 'admin',
}
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
roles: p.enum(() => Role).array().default([Role.User]),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);enum Role {
User = 'user',
Admin = 'admin',
}
export const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
roles: p.enum(() => Role).array().default([Role.User]),
},
});enum Role {
User = 'user',
Admin = 'admin',
}
@Enum({ items: () => Role, array: true, default: [Role.User] })
roles = [Role.User];enum Role {
User = 'user',
Admin = 'admin',
}
@Enum({ default: [Role.User] })
roles = [Role.User];直接映射到主键
有时你可能只想操作关系的主键。为此,你可以在 M:1 与 1:1 关系上使用 mapToPk 选项:
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
user: () => p.manyToOne(User).mapToPk(),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);export const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
user: () => p.manyToOne(User).mapToPk(),
},
});@ManyToOne(() => User, { mapToPk: true })
user: number;@ManyToOne(() => User, { mapToPk: true })
user: number;对于复合主键,这会给我们一个表示原始主键的有序元组,这正是复合主键的内部格式:
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
user: () => p.manyToOne(User).mapToPk(),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);export const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
user: () => p.manyToOne(User).mapToPk(),
},
});@ManyToOne(() => User, { mapToPk: true })
user: [string, string]; // [first_name, last_name]@ManyToOne(() => User, { mapToPk: true })
user: [string, string]; // [first_name, last_name]公式
@Formula() 装饰器可用于把某段 SQL 映射到你的实体上。该 SQL 片段可以任意复杂,甚至可以包含子查询。
const BoxSchema = defineEntity({
name: 'Box',
properties: {
objectVolume: p.integer().formula('obj_length * obj_height * obj_width'),
},
});
export class Box extends BoxSchema.class {}
BoxSchema.setClass(Box);export const Box = defineEntity({
name: 'Box',
properties: {
objectVolume: p.integer().formula('obj_length * obj_height * obj_width'),
},
});@Formula('obj_length * obj_height * obj_width')
objectVolume?: number;@Formula('obj_length * obj_height * obj_width')
objectVolume?: number;公式会被自动添加到 select 子句中。你可以把公式定义为接收 columns 对象的回调,该对象把属性名映射到它们未加引号的列引用(例如 alias.field_name)。使用 quote 辅助函数可以在所有数据库平台上正确地给标识符加引号:
import { quote } from '@mikro-orm/core';
const BoxSchema = defineEntity({
name: 'Box',
properties: {
objectVolume: p.integer().formula(cols => quote`${cols.objLength} * ${cols.objHeight} * ${cols.objWidth}`),
},
});
export class Box extends BoxSchema.class {}
BoxSchema.setClass(Box);import { quote } from '@mikro-orm/core';
export const Box = defineEntity({
name: 'Box',
properties: {
objectVolume: p.integer().formula(cols => quote`${cols.objLength} * ${cols.objHeight} * ${cols.objWidth}`),
},
});import { quote } from '@mikro-orm/core';
@Formula(cols => quote`${cols.objLength} * ${cols.objHeight} * ${cols.objWidth}`)
objectVolume?: number;import { quote } from '@mikro-orm/core';
@Formula(cols => quote`${cols.objLength} * ${cols.objHeight} * ${cols.objWidth}`)
objectVolume?: number;columns 对象:
- 把属性名映射到完整限定的
alias.field_name引用 - 与 TPT(每类型一张表)继承配合良好 —— 继承来的属性会自动使用父表的别名
- 拥有
toString(),为向后兼容返回表别名
对于更复杂的场景,你可以使用增强的回调签名,它能访问表元数据:
@Formula((cols, table) => {
return `(select count(*) from other_table where other_table.ref_id = ${table.qualifiedName}.${cols.id})`;
})
relatedCount?: number;table 参数提供:
alias:加引号的表别名name:表名schema:schema 名称(如果适用)qualifiedName:带 schema 限定的表名(schema.table或仅table)toString():为方便在模板字符串中使用,返回别名
索引
你可以通过 @Index() 装饰器定义索引,对于唯一索引可以使用 @Unique() 装饰器。你可以在实体类上使用,也可以在实体属性上使用。
关于高级索引特性 —— 包括列排序方向、NULLS 排序、前缀长度、覆盖索引(INCLUDE)、填充因子、不可见索引、聚集索引以及数据库专属选项 —— 请参见专门的索引与唯一约束指南。
要定义复杂的索引,你可以使用索引表达式。它们允许你指定最终的 create index 查询以及索引名称 —— 该名称随后用于索引 diff,因此 schema 生成器只会在它尚不存在时尝试创建它,或在实体中不再定义它时将其移除。索引表达式不绑定到任何属性,而是绑定到实体本身(你仍然可以在实体级与属性级定义它们)。
要定义索引表达式,你可以提供原始 SQL 字符串,或使用表达式回调来动态构建返回的 SQL。
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
email: p.string().unique(),
age: p.integer().nullable().index(),
born: p.date().nullable().index('born_index'),
title: p.string(),
country: p.string(),
},
indexes: [
{ properties: ['name', 'age'] }, // 复合索引,使用生成的名称
{ name: 'custom_idx_name', properties: ['name'] }, // 简单索引,使用自定义名称
// 使用表达式回调的自定义索引
// ${table.schema}、${table.name} 与 ${columns.title} 返回未加引号的标识符。
{ name: 'custom_index_country1', expression: (columns, table, indexName) => `create index \`${indexName}\` on \`${table.schema}\`.\`${table.name}\` (\`${columns.country}\`)` },
// 使用 quote 辅助函数自动给标识符加引号。
{ name: 'custom_index_country2', expression: (columns, table, indexName) => quote`create index ${indexName} on ${table} (${columns.country})` },
// 使用 raw 函数自动给标识符加引号。
{ name: 'custom_index_country3', expression: (columns, table, indexName) => raw(`create index ?? on ?? (??)`, [indexName, table, columns.country]) },
],
uniques: [
{ properties: ['name', 'email'] },
],
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);export const Author = defineEntity({
name: 'Author',
properties: {
email: p.string().unique(),
age: p.integer().nullable().index(),
born: p.date().nullable().index('born_index'),
title: p.string(),
country: p.string(),
},
indexes: [
{ properties: ['name', 'age'] }, // 复合索引,使用生成的名称
{ name: 'custom_idx_name', properties: ['name'] }, // 简单索引,使用自定义名称
// 使用表达式回调的自定义索引
// ${table.schema}、${table.name} 与 ${columns.title} 返回未加引号的标识符。
{ name: 'custom_index_country1', expression: (columns, table, indexName) => `create index \`${indexName}\` on \`${table.schema}\`.\`${table.name}\` (\`${columns.country}\`)` },
// 使用 quote 辅助函数自动给标识符加引号。
{ name: 'custom_index_country2', expression: (columns, table, indexName) => quote`create index ${indexName} on ${table} (${columns.country})` },
// 使用 raw 函数自动给标识符加引号。
{ name: 'custom_index_country3', expression: (columns, table, indexName) => raw(`create index ?? on ?? (??)`, [indexName, table, columns.country]) },
],
uniques: [
{ properties: ['name', 'email'] },
],
});@Entity()
@Index({ properties: ['name', 'age'] }) // 复合索引,使用生成的名称
@Index({ name: 'custom_idx_name', properties: ['name'] }) // 简单索引,使用自定义名称
@Unique({ properties: ['name', 'email'] })
export class Author {
@Property()
@Unique()
email!: string;
@Property()
@Index() // 生成的名称
age?: number;
@Index({ name: 'born_index' })
@Property()
born?: string;
// 使用原始 SQL 字符串表达式的自定义索引
@Index({ name: 'custom_index_expr', expression: 'alter table `author` add index `custom_index_expr`(`title`)' })
@Property()
title!: string;
// 使用表达式回调的自定义索引
// ${table.schema}、${table.name} 与 ${columns.title} 返回未加引号的标识符。
@Index({ name: 'custom_index_country1', expression: (columns, table, indexName) => `create index \`${indexName}\` on \`${table.schema}\`.\`${table.name}\` (\`${columns.country}\`)` })
// 使用 quote 辅助函数自动给标识符加引号。
@Index({ name: 'custom_index_country2', expression: (columns, table, indexName) => quote`create index ${indexName} on ${table} (${columns.country})` })
// 使用 raw 函数自动给标识符加引号。
@Index({ name: 'custom_index_country3', expression: (columns, table, indexName) => raw(`create index ?? on ?? (??)`, [indexName, table, columns.country]) })
@Property()
country!: string;
}@Entity()
@Index({ properties: ['name', 'age'] }) // 复合索引,使用生成的名称
@Index({ name: 'custom_idx_name', properties: ['name'] }) // 简单索引,使用自定义名称
@Unique({ properties: ['name', 'email'] })
export class Author {
@Property()
@Unique()
email!: string;
@Property()
@Index() // 生成的名称
age?: number;
@Index({ name: 'born_index' })
@Property()
born?: string;
// 使用原始 SQL 字符串表达式的自定义索引
@Index({ name: 'custom_index_expr', expression: 'alter table `author` add index `custom_index_expr`(`title`)' })
@Property()
title!: string;
// 使用表达式回调的自定义索引
// ${table.schema}、${table.name} 与 ${columns.title} 返回未加引号的标识符。
@Index({ name: 'custom_index_country1', expression: (columns, table, indexName) => `create index \`${indexName}\` on \`${table.schema}\`.\`${table.name}\` (\`${columns.country}\`)` })
// 使用 quote 辅助函数自动给标识符加引号。
@Index({ name: 'custom_index_country2', expression: (columns, table, indexName) => quote`create index ${indexName} on ${table} (${columns.country})` })
// 使用 raw 函数自动给标识符加引号。
@Index({ name: 'custom_index_country3', expression: (columns, table, indexName) => raw(`create index ?? on ?? (??)`, [indexName, table, columns.country]) })
@Property()
country!: string;
}
检查约束
你可以通过 @Check() 装饰器定义检查约束。你可以在实体类上使用,也可以在实体属性上使用。它有一个必填的 expression 属性,可以是字符串,也可以是接收"属性名 → 列名"映射的回调。注意,如果你想要属性名的 TypeScript 提示,需要使用泛型类型参数。
检查约束目前仅在 postgres 驱动中受支持。
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
price1: p.integer(),
price2: p.integer(),
price3: p.integer(),
},
checks: [
{ expression: 'price1 >= 0' },
{ name: 'foo', expression: columns => `${columns.price1} >= 0` },
{ expression: columns => `${columns.price1} >= 0` },
{ propertyName: 'price2', expression: 'price2 >= 0' },
{ propertyName: 'price3', expression: columns => `${columns.price3} >= 0` },
],
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
price1: p.integer(),
price2: p.integer(),
price3: p.integer(),
},
checks: [
{ expression: 'price1 >= 0' },
{ name: 'foo', expression: columns => `${columns.price1} >= 0` },
{ expression: columns => `${columns.price1} >= 0` },
{ propertyName: 'price2', expression: 'price2 >= 0' },
{ propertyName: 'price3', expression: columns => `${columns.price3} >= 0` },
],
});@Entity()
// 基于表名生成名称
@Check({ expression: 'price1 >= 0' })
// 使用显式名称
@Check({ name: 'foo', expression: (columns, table) => `${columns.price1} >= 0` })
export class Book {
@PrimaryKey()
id!: number;
@Property()
price1!: number;
@Property()
@Check({ expression: 'price2 >= 0' })
price2!: number;
@Property({ check: (columns, table) => `${columns.price3} >= 0` })
price3!: number;
}@Entity()
// 基于表名生成名称
@Check({ expression: 'price1 >= 0' })
// 使用显式名称
@Check({ name: 'foo', expression: (columns, table) => `${columns.price1} >= 0` })
export class Book {
@PrimaryKey()
id!: number;
@Property()
price1!: number;
@Property()
@Check({ expression: 'price2 >= 0' })
price2!: number;
@Property({ check: (columns, table) => `${columns.price3} >= 0` })
price3!: number;
}排他约束(PostgreSQL)
PostgreSQL 的 EXCLUDE 约束与 CHECK 共享相同的生命周期(表级约束,通过 ALTER TABLE … DROP CONSTRAINT 删除),因此 @Check() 接受完整的约束体作为 expression,并在其以 EXCLUDE 开头时原样输出:
@Entity()
@Check({
name: 'room_booking_no_overlap',
expression: 'exclude using gist (room_id with =, during with &&)',
})
export class RoomBooking {
@PrimaryKey()
id!: number;
@Property()
room_id!: number;
@Property({ columnType: 'tstzrange' })
during!: string;
}当约束在非范围类型上使用 = 时,需要 btree_gist 扩展。schema 生成器会像处理检查约束那样通过自省往返 EXCLUDE 约束 —— 不会产生额外的 diff 抖动。
数据库触发器
你可以通过 @Trigger() 装饰器,或 defineEntity/EntitySchema 中的 triggers 选项定义数据库触发器。触发器由 schema 生成器与迁移系统管理 —— 它们会被自动创建、更新与移除。
每个触发器都需要 timing(before、after 或 instead of)、一个或多个 events(insert、update、delete、truncate),以及 body(要执行的 SQL)或 expression(原始 DDL 逃生舱)二者之一。
body 可以是字符串,也可以是接收列名映射的回调,与检查约束类似。ORM 会为每种数据库驱动生成相应的 DDL:
- PostgreSQL:创建独立的函数与触发器
- MySQL/MariaDB/SQLite:为每个事件创建一个触发器(这些数据库要求如此)
- MSSQL:创建一个带多个事件的触发器(仅支持
after与instead of—— MSSQL 不支持before触发器)
@Trigger({
name: 'update_timestamp',
timing: 'before',
events: ['insert', 'update'],
body: `NEW.updated_at = NOW(); RETURN NEW`,
})
@Entity()
class Product {
@PrimaryKey()
id!: number;
@Property()
updatedAt!: Date;
}使用 defineEntity:
const Product = defineEntity({
name: 'Product',
properties: {
id: p.integer().primary(),
updatedAt: p.date(),
},
triggers: [{
name: 'update_timestamp',
timing: 'before',
events: ['insert', 'update'],
body: columns => raw`NEW.${columns.updatedAt} = NOW(); RETURN NEW`,
}],
});若要完全控制生成的 DDL,请改用 expression 逃生舱而不是 body:
@Trigger({
name: 'my_trigger',
timing: 'after',
events: ['insert'],
expression: `create trigger "my_trigger" after insert on "product" for each row execute function my_existing_fn()`,
})数据库触发器仅受 SQL 驱动支持。在 MongoDB 实体上定义触发器会抛出错误。
使用
expression时,后续的 schema diff 无法检测到表达式值的变化。要更新基于表达式的触发器,请手动删除并重建它。对于应当由迁移系统完整管理的触发器,请优先使用body。
自定义类型
你可以通过继承 Type 抽象类定义自定义类型。它有 4 个可选方法:
convertToDatabaseValue(value: any, platform: Platform): any把值从其 JS 表示转换为该类型的数据库表示。
convertToJSValue(value: any, platform: Platform): any把值从其数据库表示转换为该类型的 JS 表示。
toJSON(value: any, platform: Platform): any把值从其 JS 表示转换为该类型的序列化 JSON 形式。默认使用运行时值。
getColumnType(prop: EntityProperty, platform: Platform): string获取该类型字段的 SQL 声明片段。
更多信息可以在自定义类型一节找到。
惰性标量属性
你可以把任意属性标记为 lazy: true,从而把它从 select 子句中省略。这对那些体积过大、你只想偶尔取用的属性很有帮助,比如文章的全文。
const BookSchema = defineEntity({
name: 'Book',
properties: {
text: p.text().lazy(),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);export const Book = defineEntity({
name: 'Book',
properties: {
text: p.text().lazy(),
},
});@Property({ columnType: 'text', lazy: true })
text: string;@Property({ columnType: 'text', lazy: true })
text: string;你可以使用 populate 参数来加载它们。
const b1 = await em.find(Book, 1); // 这会省略 `text` 属性
const b2 = await em.find(Book, 1, { populate: ['text'] }); // 这会加载 `text` 属性如果实体已经加载完成,而你又需要 populate 一个惰性标量属性,可能需要在
FindOptions中传入refresh: true。
ScalarReference 包装器
与 Reference 包装器类似,你也可以用 Ref 把惰性标量包装成 ScalarReference 对象。对于非对象类型,Ref 类型会自动解析为 ScalarReference,因此下面是正确的:
@Property({ lazy: true, ref: true })
passwordHash!: Ref<string>;const user = await em.findOne(User, 1);
const passwordHash = await user.passwordHash.load();对于类对象类型,如果你选择使用引用包装器,应当显式使用 ScalarRef<T> 类型。例如,你可能想惰性加载一个很大的 JSON 值:
@Property({ type: 'json', nullable: true, lazy: true, ref: true })
// ReportParameters 是一个对象类型,可以想象它定义在别处。
reportParameters!: ScalarRef<ReportParameters | null>; 请记住,一旦某个标量值通过 ScalarReference 管理,通过 MikroORM 受管对象访问它时总会返回 ScalarReference 包装器。当该属性同时是 nullable 时这会让人困惑,因为 ScalarReference 始终为真值。在这种情况下,你应当像上面那样通过 ScalarReference<T> 的类型参数把可空性告知类型系统。下面是这一切如何运作的示例:
// 假设 id 为 "1" 的 Report 在数据库中没有 reportParameters。
const report = await em.findOne(Report, 1);
if (report.reportParameters) {
// 输出 Ref<?>,而非实际值。**总会执行***。
console.log(report.reportParameters);
//@ts-expect-error 在引用被加载之前 $/.get() 不可用。
// const mistake = report.reportParameters.$
}
const populatedReport = await em.populate(report, ['reportParameters']);
// 输出 `null`
console.log(populatedReport.reportParameters.$); 私有属性访问器
当你使用由一对公有 get/set 支撑的私有属性时,请用 accessor 选项指向另一侧。
对于标量/内嵌属性,列名由访问器名称推断(例如
_email配合accessor: 'email'会产生列_email)。对于 to-one 关系,只有当属性名符合约定俗成的_前缀后备字段形态时才会触发这一推断 ——_draft配合accessor: 'draft'会产生外键列draft_id,而不带前缀的属性名则保持原样。
依赖约定是脆弱的。请优先通过
fieldName(标量)或joinColumn(to-one 关系)显式设置列名 —— 两者都会覆盖推断出的值。
如果 accessor 选项指向了某个东西,ORM 会直接使用后备属性:
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
// ORM 会直接使用后备字段
email: p.string().accessor('_email'),
},
});
export class User extends UserSchema.class {
private _email!: unknown;
get email(): unknown {
return this._email;
}
set email(email: unknown) {
this._email = email;
}
}
UserSchema.setClass(User);export class User {
id!: number;
private _email!: unknown;
get email(): unknown {
return this._email;
}
set email(email: unknown) {
this._email = email;
}
}
export const UserSchema = defineEntity({
class: User,
properties: {
id: p.integer().primary(),
// ORM 会直接使用后备字段
email: p.string().accessor('_email'),
},
});@Entity()
export class User {
@PrimaryKey()
id!: number;
// ORM 会直接使用后备字段
@Property({ accessor: 'email' })
private _email: string;
get email() {
return this._email;
}
set email(email: string) {
this._email = email;
}
}@Entity()
export class User {
@PrimaryKey()
id!: number;
// ORM 会直接使用后备字段
@Property({ accessor: 'email' })
private _email: string;
get email() {
return this._email;
}
set email(email: string) {
this._email = email;
}
}如果你希望 ORM 在内部使用访问器(例如用于水合或变更跟踪),请改为在 get/set 属性上使用 accessor: true。当你想用原生私有属性作为后备字段时,这很方便。
const UserSchema = defineEntity({
name: 'User',
// 原生私有字段需要构造函数
forceConstructor: true,
properties: {
id: p.integer().primary(),
// ORM 会在内部使用访问器
email: p.string().accessor(),
},
});
export class User extends UserSchema.class {
#email!: string;
get email() {
return this.#email;
}
set email(email: string) {
this.#email = email;
}
}
UserSchema.setClass(User);export class User {
id!: string;
#email!: string;
get email() {
return this.#email;
}
set email(email: string) {
this.#email = email;
}
}
export const UserSchema = defineEntity({
class: User,
// 原生私有字段需要构造函数
forceConstructor: true,
properties: {
id: p.integer().primary(),
// ORM 会在内部使用访问器
email: p.string().accessor(),
},
});@Entity({ forceConstructor: true })
export class User {
@PrimaryKey()
id!: number;
#email!: string;
// ORM 会在内部使用访问器
@Property({ accessor: true })
get email() {
return this.#email;
}
set email(email: string) {
this.#email = email;
}
}@Entity({ forceConstructor: true })
export class User {
@PrimaryKey()
id!: number;
#email!: string;
// ORM 会在内部使用访问器
@Property({ accessor: true })
get email() {
return this.#email;
}
set email(email: string) {
this.#email = email;
}
}虚拟属性
你可以把属性定义为虚拟的,既可以作为方法,也可以通过 JavaScript 的 get/set。
下面的示例定义了带 firstName 与 lastName 数据库字段的 User 实体,这两个字段在序列化响应中都被隐藏,取而代之的是虚拟属性 fullName(定义为经典方法)与 fullName2(定义为 JavaScript getter)。
对于 JavaScript getter,你需要提供
{ persist: false }选项,否则该值会被存入数据库。
const UserSchema = defineEntity({
name: 'User',
properties: {
firstName: p.string().hidden(),
lastName: p.string().hidden(),
fullName: p.type('method').persist(false).getter().getterName('getFullName'),
fullName2: p.type('method').persist(false).getter(),
},
});
export class User extends UserSchema.class {
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
// Opt 返回类型把该 getter 标记为创建实体时非必填
get fullName2(): Opt<string> {
return `${this.firstName} ${this.lastName}`;
}
}
UserSchema.setClass(User);export class User {
[HiddenProps]?: 'firstName' | 'lastName';
firstName!: string;
lastName!: string;
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
// Opt 返回类型把该 getter 标记为创建实体时非必填
get fullName2(): Opt<string> {
return `${this.firstName} ${this.lastName}`;
}
}
export const UserSchema = defineEntity({
class: User,
name: 'User',
properties: {
firstName: p.string().hidden(),
lastName: p.string().hidden(),
fullName: p.type('method').persist(false).getter().getterName('getFullName'),
fullName2: p.type('method').persist(false).getter(),
},
});@Entity()
export class User {
[HiddenProps]?: 'firstName' | 'lastName';
@Property({ hidden: true })
firstName!: string;
@Property({ hidden: true })
lastName!: string;
@Property({ name: 'fullName' })
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
// Opt 返回类型把该 getter 标记为创建实体时非必填
@Property({ persist: false })
get fullName2(): Opt<string> {
return `${this.firstName} ${this.lastName}`;
}
}@Entity()
export class User {
[HiddenProps]?: 'firstName' | 'lastName';
@Property({ hidden: true })
firstName!: string;
@Property({ hidden: true })
lastName!: string;
@Property({ name: 'fullName' })
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
// Opt 返回类型把该 getter 标记为创建实体时非必填
@Property({ persist: false })
get fullName2(): Opt<string> {
return `${this.firstName} ${this.lastName}`;
}
}const repo = em.getRepository(User);
const author = repo.create({ firstName: 'Jon', lastName: 'Snow' });
console.log(author.getFullName()); // 'Jon Snow'
console.log(author.fullName2); // 'Jon Snow'
console.log(wrap(author).toJSON()); // { fullName: 'Jon Snow', fullName2: 'Jon Snow' }实体文件名
从 MikroORM 4.2 开始,实体文件名不再有限制。现在也可以使用基于文件夹的发现机制在单个文件中定义多个实体。
实体默认排序
你可以使用 @Entity() 中的 orderBy 选项为实体定义默认排序。该排序会在以下情况自动应用:
- 通过
em.find()、em.findAll()等直接查询该实体 - 把该实体作为关系 populate
所有适用的排序规则都会被合并,同一字段上优先级更高的排序生效。
import { defineEntity, p } from '@mikro-orm/core';
const CommentSchema = defineEntity({
name: 'Comment',
orderBy: { createdAt: QueryOrder.DESC, id: QueryOrder.DESC },
properties: {
id: p.integer().primary(),
createdAt: p.datetime(),
text: p.string(),
post: () => p.manyToOne(Post),
},
});
export class Comment extends CommentSchema.class {}
CommentSchema.setClass(Comment);import { defineEntity, p } from '@mikro-orm/core';
export const Comment = defineEntity({
name: 'Comment',
orderBy: { createdAt: QueryOrder.DESC, id: QueryOrder.DESC },
properties: {
id: p.integer().primary(),
createdAt: p.datetime(),
text: p.string(),
post: () => p.manyToOne(Post),
},
});@Entity({ orderBy: { createdAt: QueryOrder.DESC, id: QueryOrder.DESC } })
export class Comment {
@PrimaryKey()
id!: number;
@Property()
createdAt!: Date;
@Property()
text!: string;
@ManyToOne(() => Post)
post!: Post;
}@Entity({ orderBy: { createdAt: QueryOrder.DESC, id: QueryOrder.DESC } })
export class Comment {
@PrimaryKey()
id!: number;
@Property()
createdAt!: Date;
@Property()
text!: string;
@ManyToOne()
post!: Post;
}排序优先级(从高到低)为:
- 运行时
orderBy—— 传给em.find()、collection.init()或collection.matching()的排序 - 关系级
orderBy—— 定义在@OneToMany()或@ManyToMany()装饰器上 - 实体级
orderBy—— 定义在@Entity()装饰器上
所有层级都会被合并 —— 如果你在运行时指定了 { name: 'asc' },而实体有 { createdAt: 'desc' },结果会先按 name 排序,再按 createdAt 排序。
import { defineEntity, p } from '@mikro-orm/core';
const PostSchema = defineEntity({
name: 'Post',
properties: {
id: p.integer().primary(),
comments: () => p.oneToMany(Comment).mappedBy('post'),
commentsAlphabetical: () => p.oneToMany(Comment).mappedBy('post').orderBy({ text: QueryOrder.ASC }),
},
});
export class Post extends PostSchema.class {}
PostSchema.setClass(Post);import { defineEntity, p } from '@mikro-orm/core';
export const Post = defineEntity({
name: 'Post',
properties: {
id: p.integer().primary(),
comments: () => p.oneToMany(Comment).mappedBy('post'),
commentsAlphabetical: () => p.oneToMany(Comment).mappedBy('post').orderBy({ text: QueryOrder.ASC }),
},
});@Entity()
export class Post {
@PrimaryKey()
id!: number;
@OneToMany(() => Comment, c => c.post)
comments = new Collection<Comment>(this);
@OneToMany(() => Comment, c => c.post, { orderBy: { text: QueryOrder.ASC } })
commentsAlphabetical = new Collection<Comment>(this);
}@Entity()
export class Post {
@PrimaryKey()
id!: number;
@OneToMany(() => Comment, c => c.post)
comments = new Collection<Comment>(this);
@OneToMany(() => Comment, c => c.post, { orderBy: { text: QueryOrder.ASC } })
commentsAlphabetical = new Collection<Comment>(this);
}const comments = await em.find(Comment, {});
// 按 createdAt DESC(实体级)排序,再按 id DESC
const commentsAsc = await em.find(Comment, {}, { orderBy: { createdAt: QueryOrder.ASC } });
// 按 createdAt ASC(运行时)排序,再按 id DESC(实体级)
const post = await em.findOne(Post, 1, { populate: ['comments'] });
// post.comments 按 createdAt DESC、id DESC 排序使用自定义基础实体
你可以定义自己的基础实体,包含所有实体都需要的属性,比如主键与创建/更新时间。MikroORM 支持两种继承映射策略:
- 单表继承(STI) —— 层级中的所有实体共享一张表,并用判别列区分
- 每类型一张表(TPT) —— 每个实体都有自己的表,子表通过外键关联到父表
关于这个主题的更多内容请阅读继承映射一节。
如果你通过
entities选项初始化 ORM,也需要把你的所有基础实体一并指定。
const p = defineEntity.properties;
const CustomBaseProperties = {
uuid: p.uuid().primary().onCreate(() => v4()),
createdAt: p.datetime()
.onCreate(() => new Date())
.nullable(),
updatedAt: p.datetime()
.onCreate(() => new Date())
.onUpdate(() => new Date())
.nullable(),
}const p = defineEntity.properties;
const CustomBaseProperties = {
uuid: p.uuid().primary().onCreate(() => v4()),
createdAt: p.datetime()
.onCreate(() => new Date())
.nullable(),
updatedAt: p.datetime()
.onCreate(() => new Date())
.onUpdate(() => new Date())
.nullable(),
}import { v4 } from 'uuid';
export abstract class CustomBaseEntity {
@PrimaryKey()
uuid = v4();
@Property()
createdAt = new Date();
@Property({ onUpdate: () => new Date() })
updatedAt = new Date();
}import { v4 } from 'uuid';
export abstract class CustomBaseEntity {
@PrimaryKey()
uuid = v4();
@Property()
createdAt = new Date();
@Property({ onUpdate: () => new Date() })
updatedAt = new Date();
}有一种特殊情况需要你标注基础实体 —— 如果你使用基于文件夹的发现机制,而基础实体没有使用任何装饰器(例如它没有定义任何被装饰的属性)。这种情况下,你需要把它标记为 abstract:
@Entity({ abstract: true })
export abstract class CustomBaseEntity {
// ...
}SQL 生成列
要使用生成列,你可以使用 generated 选项,或把它作为 columnType 的一部分指定:
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
firstName: p.string().length(50),
lastName: p.string().length(50),
fullName: p.string()
.length(100)
.generated(cols => `(concat(${cols.firstName}, ' ', ${cols.lastName})) stored`),
fullName2: p.string()
.length(100)
.columnType(`varchar(100) generated always as (concat(first_name, ' ', last_name)) virtual`),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
firstName: p.string().length(50),
lastName: p.string().length(50),
fullName: p.string()
.length(100)
.generated(cols => `(concat(${cols.firstName}, ' ', ${cols.lastName})) stored`),
fullName2: p.string()
.length(100)
.columnType(`varchar(100) generated always as (concat(first_name, ' ', last_name)) virtual`),
},
});@Entity()
export class User {
@PrimaryKey()
id!: number;
@Property({ length: 50 })
firstName!: string;
@Property({ length: 50 })
lastName!: string;
@Property({ length: 100, generated: cols => `(concat(${cols.firstName}, ' ', ${cols.lastName})) stored` })
fullName!: string & Opt;
@Property({ columnType: `varchar(100) generated always as (concat(first_name, ' ', last_name)) virtual` })
fullName2!: string & Opt;
}@Entity()
export class User {
@PrimaryKey()
id!: number;
@Property({ length: 50 })
firstName!: string;
@Property({ length: 50 })
lastName!: string;
@Property({ length: 100, generated: cols => `(concat(${cols.firstName}, ' ', ${cols.lastName})) stored` })
fullName!: string & Opt;
@Property({ columnType: `varchar(100) generated always as (concat(first_name, ' ', last_name)) virtual` })
fullName2!: string & Opt;
}要在 PostgreSQL 中使用生成的自增标识列,把 generated 选项设为 identity:
若要允许显式提供值,请使用
generated: 'by default as identity'。
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary().generated('identity'),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary().generated('identity'),
},
});@Entity()
export class User {
@PrimaryKey({ generated: 'identity' })
id!: number;
}@Entity()
export class User {
@PrimaryKey({ generated: 'identity' })
id!: number;
}各种主键的实体定义示例
使用 id 作为主键(SQL 驱动)
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
title: p.string(),
author: () => p.manyToOne(Author),
publisher: () => p.manyToOne(Publisher).nullable(),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
title: p.string(),
author: () => p.manyToOne(Author),
publisher: () => p.manyToOne(Publisher).nullable(),
},
});@Entity()
export class Book {
@PrimaryKey()
id!: number; // 同样支持 string
@Property()
title!: string;
@ManyToOne(() => Author)
author!: Author;
@ManyToOne(() => Publisher, { ref: true, nullable: true })
publisher?: Ref<Publisher>;
}@Entity()
export class Book {
@PrimaryKey()
id!: number; // 同样支持 string
@Property()
title!: string;
@ManyToOne()
author!: Author;
@ManyToOne()
publisher?: Ref<Publisher>;
}使用 UUID 作为主键(SQL 驱动)
const BookSchema = defineEntity({
name: 'Book',
properties: {
uuid: p.uuid().primary().onCreate(() => v4()),
title: p.string(),
author: () => p.manyToOne(Author),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);export const Book = defineEntity({
name: 'Book',
properties: {
uuid: p.uuid().primary().onCreate(() => v4()),
title: p.string(),
author: () => p.manyToOne(Author),
},
});import { v4 } from 'uuid';
@Entity()
export class Book {
@PrimaryKey()
uuid = v4();
@Property()
title!: string;
@ManyToOne(() => Author)
author!: Author;
}import { v4 } from 'uuid';
@Entity()
export class Book {
@PrimaryKey()
uuid = v4();
@Property()
title!: string;
@ManyToOne()
author!: Author;
}使用 PostgreSQL 内置的 gen_random_uuid 函数作为主键
const BookSchema = defineEntity({
name: 'Book',
properties: {
uuid: p.uuid().primary().defaultRaw('gen_random_uuid()'),
title: p.string(),
author: () => p.manyToOne(Author),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);export const Book = defineEntity({
name: 'Book',
properties: {
uuid: p.uuid().primary().defaultRaw('gen_random_uuid()'),
title: p.string(),
author: () => p.manyToOne(Author),
},
});@Entity()
export class Book {
@PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })
uuid: string;
@Property()
title!: string;
@ManyToOne(() => Author)
author!: Author;
}@Entity()
export class Book {
@PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })
uuid: string;
@Property()
title!: string;
@ManyToOne()
author!: Author;
}使用 BigInt 作为主键(MySQL 与 PostgreSQL)
从 v6 起,bigint 由原生 BigInt 类型表示,因此在装饰器选项中无需显式指定类型:
@PrimaryKey()
id: bigint;你也可以指定希望 bigint 映射到的目标类型:
@PrimaryKey({ type: new BigIntType('bigint') })
id1: bigint;
@PrimaryKey({ type: new BigIntType('string') })
id2: string;
@PrimaryKey({ type: new BigIntType('number') })
id3: number;当映射到
number类型时,JavaScript 无法表示bigint的所有可能取值 —— 只有不超过Number.MAX_SAFE_INTEGER(2^53 - 1)的值才是安全的。
const SomeEntitySchema = defineEntity({
name: 'SomeEntity',
properties: {
id: p.bigint().primary(),
},
});
export class SomeEntity extends SomeEntitySchema.class {}
SomeEntitySchema.setClass(SomeEntity);export const SomeEntity = defineEntity({
name: 'SomeEntity',
properties: {
id: p.bigint().primary(),
},
});@Entity()
export class Book {
@PrimaryKey()
id: bigint;
}@Entity()
export class Book {
@PrimaryKey()
id: bigint;
}如果你想使用原生 bigint,请阅读以下指南:使用原生 BigInt 主键。
Mongo 实体示例
const BookSchema = defineEntity({
name: 'Book',
properties: {
_id: p.type(ObjectId).primary(),
id: p.string().serializedPrimaryKey(),
title: p.string(),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);export const Book = defineEntity({
name: 'Book',
properties: {
_id: p.type(ObjectId).primary(),
id: p.string().serializedPrimaryKey(),
title: p.string(),
},
});@Entity()
export class Book {
@PrimaryKey()
_id!: ObjectId;
@SerializedPrimaryKey()
id!: string; // 主键的字符串形式,会被自动处理
@Property()
title!: string;
@ManyToOne(() => Author)
author!: Author;
}@Entity()
export class Book {
@PrimaryKey()
_id!: ObjectId;
@SerializedPrimaryKey()
id!: string; // 主键的字符串形式,会被自动处理
@Property()
title!: string;
@ManyToOne()
author!: Author;
}使用 MikroORM 的 BaseEntity(此前称为 WrappedEntity)
BaseEntity 类提供了 init、isInitialized、assign 等方法,这些方法原本需要通过 wrap() 辅助函数访问。
是否使用
BaseEntity是可选的。
import { BaseEntity } from '@mikro-orm/core';
@Entity()
export class Book extends BaseEntity {
@PrimaryKey()
id!: number;
@Property()
title!: string;
@ManyToOne()
author!: Author;
}
const book = new Book();
console.log(book.isInitialized()); // true