快速入门
在本指南中,你将学习如何使用 MikroORM 快速引导一个简单的项目。如需深入了解,请查看下面的 入门指南。
¥In this guide, you will learn how to quickly bootstrap a simple project using MikroORM. For a deeper dive, check out the Getting Started guide which follows.
如果你希望查看现有项目,则可以使用 几个示例存储库。
¥If you prefer to take a peek at an existing project, there are several example repositories available.
安装
¥Installation
首先通过你选择的包管理器安装模块。不要忘记安装数据库驱动程序:
¥First install the module via package manager of your choice. Do not forget to install the database driver as well:
- npm
- Yarn
- pnpm
# for mongodb
npm install @mikro-orm/core @mikro-orm/mongodb
# for mysql (works with mariadb too)
npm install @mikro-orm/core @mikro-orm/mysql
# for mariadb (works with mysql too)
npm install @mikro-orm/core @mikro-orm/mariadb
# for postgresql (works with cockroachdb too)
npm install @mikro-orm/core @mikro-orm/postgresql
# for sqlite
npm install @mikro-orm/core @mikro-orm/sqlite
# for better-sqlite
npm install @mikro-orm/core @mikro-orm/better-sqlite
# for libsql/turso
npm install @mikro-orm/core @mikro-orm/libsql
# for mssql
npm install @mikro-orm/core @mikro-orm/mssql
# for mongodb
yarn add @mikro-orm/core @mikro-orm/mongodb
# for mysql (works with mariadb too)
yarn add @mikro-orm/core @mikro-orm/mysql
# for mariadb (works with mysql too)
yarn add @mikro-orm/core @mikro-orm/mariadb
# for postgresql (works with cockroachdb too)
yarn add @mikro-orm/core @mikro-orm/postgresql
# for sqlite
yarn add @mikro-orm/core @mikro-orm/sqlite
# for better-sqlite
yarn add @mikro-orm/core @mikro-orm/better-sqlite
# for libsql/turso
yarn add @mikro-orm/core @mikro-orm/libsql
# for mssql
yarn add @mikro-orm/core @mikro-orm/mssql
# for mongodb
pnpm add @mikro-orm/core @mikro-orm/mongodb
# for mysql (works with mariadb too)
pnpm add @mikro-orm/core @mikro-orm/mysql
# for mariadb (works with mysql too)
pnpm add @mikro-orm/core @mikro-orm/mariadb
# for postgresql (works with cockroachdb too)
pnpm add @mikro-orm/core @mikro-orm/postgresql
# for sqlite
pnpm add @mikro-orm/core @mikro-orm/sqlite
# for better-sqlite
pnpm add @mikro-orm/core @mikro-orm/better-sqlite
# for libsql/turso
pnpm add @mikro-orm/core @mikro-orm/libsql
# for mssql
pnpm add @mikro-orm/core @mikro-orm/mssql
接下来,你需要通过以下方式在 tsconfig.json
中启用对 decorators 和 esModuleInterop
的支持:
¥Next you will need to enable support for decorators as well as esModuleInterop
in tsconfig.json
via:
装饰器是可选的,如果你使用不同的方式定义实体元数据(如
EntitySchema
),则无需启用它们。¥The decorators are opt-in, if you use a different way to define your entity metadata like
EntitySchema
, you don't need to enable them.
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true
然后在引导应用时调用 MikroORM.init
:
¥Then call MikroORM.init
as part of bootstrapping your app:
要访问驱动程序特定方法(如
em.createQueryBuilder()
),你需要从驱动程序包中导入MikroORM
/EntityManager
/EntityRepository
类。或者,你可以将orm.em
转换为从驱动程序包导出的EntityManager
:¥To access driver specific methods like
em.createQueryBuilder()
you need to import theMikroORM
/EntityManager
/EntityRepository
class from the driver package. Alternatively you can cast theorm.em
toEntityManager
exported from the driver package:import { EntityManager } from '@mikro-orm/postgresql';
const em = orm.em as EntityManager;
const qb = em.createQueryBuilder(...);
import { MikroORM } from '@mikro-orm/postgresql'; // or any other driver package
const orm = await MikroORM.init({
entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`
dbName: 'my-db-name',
});
console.log(orm.em); // access EntityManager via `em` property
你可以在 高级配置 部分中阅读有关所有可能的配置选项的更多信息。
¥You can read more about all the possible configuration options in Advanced Configuration section.
基于文件夹的发现
¥Folder-based discovery
你还可以通过 entities
数组提供存储实体的路径。路径在内部通过 globby
解析,因此你可以使用 通配符模式,包括负全局变量。
¥You can also provide paths where you store your entities via entities
array. The paths are resolved via globby
internally, so you can use globbing patterns, including negative globs.
const orm = await MikroORM.init({
entities: ['./dist/app/**/*.entity.js'],
entitiesTs: ['./src/app/**/*.entity.ts'],
// ...
});
如果你在基于文件夹的发现中遇到问题,请尝试使用 mikro-orm debug
CLI 命令检查实际正在使用的路径。
¥If you are experiencing problems with folder based discovery, try using mikro-orm debug
CLI command to check what paths are actually being used.
TypeScript 中的实体发现
¥Entity Discovery in TypeScript
默认元数据提供程序是 ReflectMetadataProvider
。如果你想使用基于 ts-morph
的发现(通过编译器 API 读取实际的 TS 类型),你需要安装 @mikro-orm/reflection
包。
¥The default metadata provider is ReflectMetadataProvider
. If you want to use ts-morph
based discovery (that reads actual TS types via the compiler API), you need to install @mikro-orm/reflection
package.
import { MikroORM } from '@mikro-orm/postgresql';
import { TsMorphMetadataProvider } from '@mikro-orm/reflection';
const orm = await MikroORM.init({
metadataProvider: TsMorphMetadataProvider,
// ...
});
在 元数据提供程序部分 中阅读有关差异的更多信息。
¥Read more about the differences in Metadata Providers section.
import { MikroORM } from '@mikro-orm/postgresql';
const orm = await MikroORM.init({
entities: ['./dist/entities/**/*.js'], // path to your JS entities (dist), relative to `baseDir`
entitiesTs: ['./src/entities/**/*.ts'], // path to your TS entities (source), relative to `baseDir`
// ...
});
重要的是
entities
将指向已编译的 JS 文件,而entitiesTs
将指向 TS 源文件。你不应该混合使用它们。¥It is important that
entities
will point to the compiled JS files, andentitiesTs
will point to the TS source files. You should not mix those.
为了使
ts-morph
发现在生产中工作,你需要部署.d.ts
声明文件。确保在你的tsconfig.json
中启用compilerOptions.declaration
。¥For
ts-morph
discovery to work in production, you need to deploy.d.ts
declaration files. Be sure to enablecompilerOptions.declaration
in yourtsconfig.json
.
你还可以使用不同的默认 ReflectMetadataProvider
,甚至可以编写自定义 ReflectMetadataProvider
。使用 EntitySchema
是定义实体的另一种方式,完全不依赖于元数据提供程序。
¥You can also use different the default ReflectMetadataProvider
or even write custom one. Using EntitySchema
is another way to define your entities and does not depend on the metadata providers at all.
import { MikroORM } from '@mikro-orm/postgresql';
const orm = await MikroORM.init({
// default since v4, so not needed to specify explicitly
metadataProvider: ReflectMetadataProvider,
// ...
});
同步初始化
¥Synchronous initialization
与异步 MikroORM.init
方法相反,你可以选择使用同步变体 initSync
。此方法有一些限制:
¥As opposed to the async MikroORM.init
method, you can prefer to use synchronous variant initSync
. This method has
some limitations:
-
首次与数据库交互时将建立数据库连接(或者你可以明确使用
orm.connect()
)¥database connection will be established when you first interact with the database (or you can use
orm.connect()
explicitly) -
不加载
config
文件,options
参数是必需的¥no loading of the
config
file,options
parameter is mandatory -
不支持基于文件夹的发现
¥no support for folder based discovery
-
不检查不匹配的包版本
¥no check for mismatched package versions
RequestContext 助手
¥RequestContext helper
现在你需要为每个请求分叉实体管理器,这样它们的 身份映射 就不会发生冲突。为此,请使用 RequestContext
助手:
¥Now you will need to fork entity manager for each request so their identity maps
will not collide. To do so, use the RequestContext
helper:
const app = express();
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
你应该将此中间件注册为请求处理程序之前和使用 ORM 的任何自定义中间件之前的最后一个中间件。当你在请求处理中间件(如
queryParser
或bodyParser
)之前注册它时可能会出现问题,因此一定要在它们之后注册上下文。¥You should register this middleware as the last one just before request handlers and before any of your custom middleware that is using the ORM. There might be issues when you register it before request processing middleware like
queryParser
orbodyParser
, so definitely register the context after them.
有关 RequestContext
的更多信息,请参阅 此处。
¥More info about RequestContext
is described here.
实体定义
¥Entity definition
现在你可以开始定义你的实体(在其中一个 entities
文件夹中)。简单实体可能如下所示:
¥Now you can start defining your entities (in one of the entities
folders). This is how a simple entity can look like:
@Entity()
export class Book {
@PrimaryKey()
id: bigint;
@Property()
title: string;
@ManyToOne(() => Author)
author: Author;
@ManyToMany(() => BookTag)
tags = new Collection<BookTag>(this);
constructor(title: string, author: Author) {
this.title = title;
this.author = author;
}
}
或者如果你想使用 UUID 主键:
¥Or if you want to use UUID primary key:
import { v4 } from 'uuid';
@Entity()
export class Book {
@PrimaryKey({ type: 'uuid' })
uuid = v4();
// ...
}
有关 定义实体部分 文档中的更多信息,请参阅。
¥More information can be found in defining entities section in docs.
EntityManager
当你定义实体后,你可以通过 EntityManager
开始使用 ORM。
¥When you have your entities defined, you can start using ORM either via EntityManager
.
要将实体状态保存到数据库,你需要将其持久化。Persist 确定是否使用 insert
或 update
并计算适当的变更集。尚未持久化的实体引用(没有标识符)将自动级联持久化。
¥To save entity state to database, you need to persist it. Persist determines whether to use insert
or update
and
computes appropriate change-set. Entity references that are not persisted yet (does not have identifier) will be cascade
persisted automatically.
// use constructors in your entities for required parameters
const author = new Author('Jon Snow', 'snow@wall.st');
author.born = new Date();
const publisher = new Publisher('7K publisher');
const book1 = new Book('My Life on The Wall, part 1', author);
book1.publisher = publisher;
const book2 = new Book('My Life on The Wall, part 2', author);
book2.publisher = publisher;
const book3 = new Book('My Life on The Wall, part 3', author);
book3.publisher = publisher;
// just persist books, author and publisher will be automatically cascade persisted
await em.persist([book1, book2, book3]).flush();
要从数据库获取实体,你可以使用 EntityManager
中的 find()
和 findOne()
:
¥To fetch entities from database you can use find()
and findOne()
of EntityManager
:
const authors = em.find(Author, {});
for (const author of authors) {
console.log(author); // instance of Author entity
console.log(author.name); // Jon Snow
for (const book of author.books) { // iterating books collection
console.log(book); // instance of Book entity
console.log(book.title); // My Life on The Wall, part 1/2/3
}
}
查看有关 与 EntityManager
配合使用 的文档。
¥Take a look at docs about working with EntityManager
.
设置命令行工具
¥Setting up the Commandline Tool
MikroORM 附带了许多在开发过程中非常有用的命令行工具,例如 SchemaGenerator
和 EntityGenerator
。你可以从 NPM 二进制目录中调用此命令或使用 npx
:
¥MikroORM ships with a number of command line tools that are very helpful during development, like SchemaGenerator
and EntityGenerator
. You can call this command from the NPM binary directory or use npx
:
要使用 CLI,请先在本地安装
@mikro-orm/cli
包。版本需要与@mikro-orm/core
包保持一致。¥To work with the CLI, first install
@mikro-orm/cli
package locally. The version needs to be aligned with the@mikro-orm/core
package.
# install the CLI package first!
$ yarn add @mikro-orm/cli
# manually
$ node node_modules/.bin/mikro-orm
# via npx
$ npx mikro-orm
# or via yarn
$ yarn mikro-orm
为了让 CLI 能够访问你的数据库,你需要创建一个导出 ORM 配置的配置文件。
¥For CLI to be able to access your database, you will need to create a configuration file that exports your ORM configuration(s).
默认情况下,相对于当前工作目录的以下路径按此顺序搜索:
¥By default, the following paths, relative to the current working directory, are searched in this order:
./src/mikro-orm.config.ts
./mikro-orm.config.ts
./dist/mikro-orm.config.js
./build/mikro-orm.config.js
./src/mikro-orm.config.js
./mikro-orm.config.js
你可以在 package.json
中设置 ORM 配置文件的可能路径数组。package.json
文件可以位于当前工作目录中,也可以位于其父文件夹中。
¥You can set up array of possible paths to ORM config files in package.json
. The package.json
file can be located in the current working directory, or in one of its parent folders.
{
"name": "your-app",
"dependencies": { ... },
"mikro-orm": {
"configPaths": [
"./src/mikro-orm.config.ts",
"./dist/mikro-orm.config.js"
]
}
}
控制这些 CLI 相关设置的另一种方法是使用环境变量:
¥Another way to control these CLI-related settings is with the environment variables:
-
MIKRO_ORM_CLI_CONFIG
:ORM 配置文件的路径¥
MIKRO_ORM_CLI_CONFIG
: the path to ORM config file -
MIKRO_ORM_CLI_USE_TS_NODE
:注册ts-node
以获得 TypeScript 支持¥
MIKRO_ORM_CLI_USE_TS_NODE
: registerts-node
for TypeScript support -
MIKRO_ORM_CLI_TS_CONFIG_PATH
:tsconfig.json 的路径(用于 ts-node)¥
MIKRO_ORM_CLI_TS_CONFIG_PATH
: path to the tsconfig.json (for ts-node) -
MIKRO_ORM_CLI_ALWAYS_ALLOW_TS
:启用.ts
文件以在没有 ts-node 的情况下使用¥
MIKRO_ORM_CLI_ALWAYS_ALLOW_TS
: enable.ts
files to use without ts-node -
MIKRO_ORM_CLI_VERBOSE
:启用详细日志记录(例如,在播种机或模式差异中使用的打印查询)¥
MIKRO_ORM_CLI_VERBOSE
: enable verbose logging (e.g. print queries used in seeder or schema diffing)
MikroORM 将始终尝试根据 configPaths
中的顺序加载第一个可用的配置文件。当你明确禁用 useTsNode
或 ts-node
尚未注册或检测到时,TS 配置文件将被忽略。
¥MikroORM will always try to load the first available config file, based on the order in configPaths
. When you have useTsNode
explicitly disabled or ts-node
is not already registered nor detected, TS config files will be ignored.
你还可以通过 --config
选项指定配置路径:
¥You can also specify the config path via --config
option:
$ npx mikro-orm debug --config ./my-config.ts
从 v6.3 开始,CLI 将始终尝试使用 TS 配置文件,即使没有通过 package.json
文件中的 useTsNode
标志明确启用它。你仍然可以使用它来明确禁用 TS 支持。请记住,安装 ts-node
仍然是 TS 支持工作的必要条件。useTsNode
仅对 CLI 有效。
¥Since v6.3, the CLI will always try to use TS config file, even without explicitly enabling it via useTsNode
flag in your package.json
file. You can still use it to disable the TS support explicitly. Keep in mind that having ts-node
installed is still required for the TS support to work. The useTsNode
has effect only on the CLI.
你的配置文件可能会在数组中导出多个配置对象。不同的配置中必须有一个 contextName
。如果未指定 contextName
,则将其视为名称 "default"。你可以使用 MIKRO_ORM_CONTEXT_NAME
环境变量或 --contextName
命令行选项来选择具有特定 contextName
的配置以用于 CLI。有关配置对象的详细信息,请参阅 below。
¥Your configuration file may export multiple configuration objects in an array. The different configurations must have a contextName
in them. If no contextName
is specified, it is treated as the name "default". You can use the MIKRO_ORM_CONTEXT_NAME
environment variable or the --contextName
command line option to pick a configuration with a particular contextName
to use for the CLI. See below for details on the config object.
CLI 帮助中列出了所有可用的命令:
¥All available commands are listed in the CLI help:
$ npx mikro-orm
Usage: mikro-orm <command> [options]
Commands:
mikro-orm cache:clear Clear metadata cache
mikro-orm cache:generate Generate metadata cache
mikro-orm generate-entities Generate entities based on current database
schema
mikro-orm database:create Create your database if it does not exist
mikro-orm database:import <file> Imports the SQL file to the database
mikro-orm seeder:run Seed the database using the seeder class
mikro-orm seeder:create <seeder> Create a new seeder class
mikro-orm schema:create Create database schema based on current
metadata
mikro-orm schema:drop Drop database schema based on current
metadata
mikro-orm schema:update Update database schema based on current
metadata
mikro-orm schema:fresh Drop and recreate database schema based on
current metadata
mikro-orm migration:create Create new migration with current schema
diff
mikro-orm migration:up Migrate up to the latest version
mikro-orm migration:down Migrate one step down
mikro-orm migration:list List all executed migrations
mikro-orm migration:check Check if migrations are needed. Useful for
bash scripts.
mikro-orm migration:pending List all pending migrations
mikro-orm migration:fresh Clear the database and rerun all migrations
mikro-orm debug Debug CLI configuration
Options:
--config Set path to the ORM configuration file [array]
--contextName Set name of config to load out of the ORM configuration
file. Used when config file exports an array or a function
[string] [default: "default"]
-v, --version Show version number [boolean]
-h, --help Show help [boolean]
Examples:
mikro-orm schema:update --run Runs schema synchronization
要验证你的设置,你可以使用 mikro-orm debug
命令。
¥To verify your setup, you can use mikro-orm debug
command.
运行 MikroORM.init() 而不带参数
¥Running MikroORM.init() without arguments
正确设置 CLI 配置后,你可以在应用中调用 MikroORM.init()
时省略 options
参数。配置的加载方式与使用 MikroORM CLI 时的加载方式类似。
¥When a CLI config is properly set up, you can omit the options
parameter when calling MikroORM.init()
in your app. The configuration is loaded similarly to how it is loaded when using the MikroORM CLI.
当你运行应用时(只要它是 process.argv
的一部分),命令行中的 --config
标志也会受到尊重,而不仅仅是在你使用 CLI 时。
¥The --config
flag from the command line will be respected also when you run your app (as long as it is part of process.argv
), not just when you use the CLI.
$ node ./dist/index.js --config ./my-orm-config.js
这可能会与其他工具(如 jest
)发生冲突,这些工具也支持通过 --config
参数覆盖配置路径。在这些情况下,你可以使用 MIKRO_ORM_CONFIG_ARG_NAME
环境变量将参数名称更改为 config
以外的其他名称:
¥This might introduce a conflict with other tools like jest
that also support overriding the config path via --config
argument. In those cases you can use the MIKRO_ORM_CONFIG_ARG_NAME
environment variable to change the argument name to something other than config
:
$ MIKRO_ORM_CONFIG_ARG_NAME=mikro-orm-config \
node ./dist/index.js --mikro-orm-config ./my-orm-config.js
jest
不允许无法识别的参数,要使用自定义配置运行测试,你可以将其与MIKRO_ORM_CLI_CONFIG
环境变量一起使用以指向测试配置。¥
jest
does not allow unrecognised parameters, to run tests with a custom configuration you can use this together withMIKRO_ORM_CLI_CONFIG
environment variable to point to a test config.
目前,process.argv
会自动分析以实现向后兼容性。这已弃用,将在 v7 中删除。仍可使用 MikroORM CLI 的 --config
。如果你希望应用分析 process.argv
,你可以手动执行此操作,然后加载 ORM 配置并将其明确指定给 MikroORM.init()
。
¥Currently, process.argv
is automatically analyzed for backwards compatibility. This is deprecated and will be removed in v7. Using --config
with the MikroORM CLI will still be available. If you want your application to analyze process.argv
, you can manually do so, and then load the ORM config and explicitly specify it to MikroORM.init()
.
默认情况下,运行应用时不会考虑 TS 配置文件,除非你通过 ts-node
运行它。你可以在 package.json
文件中使用 alwaysAllowTs
选项,这样即使未使用 ts-node
也可以检查 TS 文件,也可以在 MikroORM CLI 中使用。如果你通过 Bun 运行应用,这会很方便。
¥By default, TS config files are not considered when running your app, unless you run it via ts-node
. You can use the alwaysAllowTs
option in your package.json
file, which will enable checking the TS files even if ts-node
is not used, as well as in the MikroORM CLI. This can be handy if you run your app via Bun.
请注意,如果你使用使用摇树的打包器,则自动从配置路径中加载配置文件可能会失败。由于配置文件未在任何静态位置引用,因此不会被编译 - 为此,最好的方法是明确提供配置:
¥Note that automatically loading the config file out of the config paths may fail if you use bundlers that use tree shaking. As the config file is not referenced anywhere statically, it would not be compiled - for that the best approach is to provide the config explicitly:
import config from './mikro-orm.config';
const orm = await MikroORM.init(config);
配置文件结构
¥Configuration file structure
创建配置对象的首选方式是使用 defineConfig
助手。它甚至会在 JavaScript 文件中提供智能感知,而无需通过 jsdoc 进行类型提示:
¥Preferred way of creating to the configuration object is with the defineConfig
helper. It will provide intellisense even in JavaScript files, without the need for type hints via jsdoc:
import { defineConfig } from '@mikro-orm/sqlite';
export default defineConfig({
entities: [Author, Book, BookTag],
dbName: 'my-db-name',
// this is inferred as you import `defineConfig` from sqlite package
// driver: SqliteDriver,
});
如果你从驱动程序包中导入助手,使用 defineConfig
还会自动为你推断驱动程序选项。这意味着你不必明确提供 driver
选项。
¥Using defineConfig
also automatically infers the driver option for you if you import the helper from the driver package. This means you don't have to provide the driver
option explicitly.
或者,你可以使用 Options
类型:
¥Alternatively, you can use the Options
type:
import { Options } from '@mikro-orm/sqlite';
const config: Options = {
entities: [Author, Book, BookTag],
dbName: 'my-db-name',
driver: SqliteDriver,
};
export default config;
你还可以导出不同配置的数组以用于不同目的。例如,你可以为 CLI 导出一个配置对象,为你的应用导出另一个配置对象。数组中的每个配置都需要有一个不同的 contextName
值(省略它与将其设置为 "default" 相同),如下所示:
¥You can also export array of different configs for different purposes. For example, you may export one config object for CLI, and another for your app. Each config in the array needs to have a distinct contextName
value (omitting it is same as setting it to "default"), like so:
import { defineConfig } from '@mikro-orm/postgresql';
export default [
defineConfig({
contextName: 'default',
entities: [Author, Book, BookTag],
dbName: 'my-db-name',
user: 'app',
// other credentials and settings
}),
defineConfig({
contextName: 'super',
entities: [Author, Book, BookTag],
dbName: 'my-db-name',
user: 'admin',
// other credentials and settings
}),
];
这反过来使你能够在应用中运行 MikroORM.init()
而无需参数(并与用户 "app" 连接),而在 CLI(你可能需要更高的权限)中,你可以使用
¥Which in turn enables you to run MikroORM.init()
in your app without arguments (and connect with the user "app"), while in CLI (where you may need higher privileges), you can use
$ npx mikro-orm --contextName=super
你还可以导出一个函数,该函数将使用 contextName
调用,并且可以为该名称提供一个配置对象,或者如果你希望该名称出错,则不返回任何内容。这在多租户设置中特别有用。
¥You can also export a function, which will be called with a contextName
, and can give a configuration object for that name, or otherwise return nothing if you wish to error on that name instead. This can be particularly useful in multi-tenant setups.
例如,如果你有
¥For example, if you have
import { defineConfig } from '@mikro-orm/postgresql';
export default (contextName: string) => defineConfig({
entities: [Author, Book, BookTag],
dbName: `tenant_${contextName}`,
user: 'app',
// other credentials and settings
});
然后,你需要启动应用并将 MIKRO_ORM_CONTEXT_NAME
环境变量设置为 example1
以加载数据库 tenant_example1
,同样,在运行 CLI 时,你可以使用
¥then you will need to start your app with the MIKRO_ORM_CONTEXT_NAME
environment variable set to example1
to load the database tenant_example1
, and similarly, when running CLI, you can use
$ npx mikro-orm --contextName=example1
对该特定租户的数据库实例进行操作。不指定任何一个选项都会将你指向 "tenant_default" 数据库。
¥to operate on that particular tenant's database instance. Not specifying either option will point you to the "tenant_default" database.
你还可以组合数组和工厂函数。数组成员将是首选,并且数组中的任何函数都将从上到下执行。第一个返回对象的函数将是最终使用的函数。
¥You can also combine arrays and factory functions. Array members will be preferred, and any functions in the array will be executed from top to bottom. The first function to return an object will be what ends up being used.
例如,你可以在配置文件中拥有
¥For example, you can have in your config file
import { defineConfig } from '@mikro-orm/postgresql';
export default [
defineConfig({
contextName: 'default',
entities: [Author, Book, BookTag],
dbName: 'demo',
user: 'app',
// other credentials and settings
}),
defineConfig({
contextName: 'super',
entities: [Author, Book, BookTag],
dbName: 'demo',
user: 'admin',
// other credentials and settings
}),
(contextName: string) => {
if (!contextName.startsWith('use:')) {
return;
}
return defineConfig({
contextName,
entities: [Author, Book, BookTag],
dbName: `tenant_${contextName.split(':', 2)[1]}`,
user: 'app',
// other credentials and settings
});
},
(contextName: string) => {
if (!contextName.startsWith('edit:')) {
return;
}
return defineConfig({
contextName,
entities: [Author, Book, BookTag],
dbName: `tenant_${contextName.split(':', 2)[1]}`,
user: 'admin',
// other credentials and settings
});
}
];
这将允许你在 CLI 中未指定 MIKRO_ORM_CONTEXT_NAME
或 --contextName
选项时使用 "app" 用户运行 "demo" 数据库。指定名称 "super" 将使用 "admin" 用户运行 "demo" 数据库,指定 "use:example1" 将使用 "app" 用户加载 "tenant_example1" 数据库,指定 "edit:example1" 将使用 "admin" 用户加载 "tenant_example1" 数据库。
¥which will let you run the "demo" database with "app" user whenever you do not specify MIKRO_ORM_CONTEXT_NAME
or the --contextName
option in CLI. Specifying "super" for the name will run the "demo" database with the "admin" user, specifying "use:example1" will load the "tenant_example1" database with the "app" user, and specifying "edit:example1" will load the "tenant_example1" database with the "admin" user.