前言
@wf-cms/egg-cms-database 是一个针对企业级 egg-cms 的数据库管理工具,为企业提供了方便快捷的数据库管理方式,并且拓展了 egg-cms 框架的功能。本文将详细介绍该 npm 包的使用方法,包括安装、配置和API说明,希望对前端开发人员有所帮助。
安装
首先,在命令行中输入以下命令进行安装:
npm install @wf-cms/egg-cms-database --save
当然,也可以使用 yarn 安装:
yarn add @wf-cms/egg-cms-database
配置
在 egg-cms 中使用数据库管理工具需要进行相关配置。在 egg-cms 的 config 文件夹中,新建 database.js 文件,按照以下方式进行配置:
-- -------------------- ---- -------
-------------- - -
--------- -
------- -------- -- -----
----------- -
----- ------------
--------- -------
----- -------
--------- --
-
-
-API 说明
连接数据库
首先,需要初始化数据库连接,在 app.js 文件中引入该模块并调用 database.init() 方法。
// app.js
const database = require('@wf-cms/egg-cms-database');
database.init(app);建立映射
使用该模块建立数据库映射是一种更方便的方式,可以快速生成数据库表和 Model,并且不需要过多的代码。以下是简单的映射示例:
-- -------------------- ---- -------
----- - ------- - - ------------------------
----- - ------------ - - ------------------------------------
----- - ---- - - --------------
----- -
-------- -
--- -
----- ------------------
----------- -----
-------------- ----
--
----- -
----- ---------------------
---------- -----
--
---- -
----- ------------------
---------- -----
--
--------- -
----- -------------------
---------- -----
-
-
-
---
---------------------- ----- -
----- ----------------------------- --- -- -------------
---- ----------------------
--------- --------------------------
---
-------------- - --- -- -
----- - ---------- - -- -- --------- - - ----
--------------------- -- -- -
----- ---------------------
---
------ -
-------
--
--以上示例中,我们定义了 User Model,并且对其进行了一系列字段的配置。在 factory.define() 方法中,则是定义了如何生成一个 User 对象。
数据库操作
在 egg-cms 中,对数据库进行增删改查操作时,可以使用 app.databases 提供的方法进行,使用方法如下:
插入数据
await app.databases.tables.user.create({
name: '张三',
age: 18,
birthday: '2000-01-01'
});更新数据
await app.databases.tables.user.update({
name: '李四'
}, {
where: {
id: 1
}
});删除数据
await app.databases.tables.user.destroy({
where: {
id: 1
}
});查询数据
const user = await app.databases.tables.user.findOne({
where: {
id: 1
}
});配置文件说明
在 database.js 文件中,有以下参数可供配置:
配置项
| Key | Type | Default | Required | Description |
|---|---|---|---|---|
| client | String | - | ✓ | 数据库类型 |
| connection.host | String | localhost | ✓ | 数据库地址 |
| connection.port | Number | 端口号 | ✓ | 端口号 |
| connection.database | String | - | ✓ | 数据库名称 |
| connection.user | String | - | ✓ | 数据库用户 |
| connection.password | String | - | ✓ | 数据库密码 |
| connection.timezone | String | UTC | 时区 | |
| connection.logging | Function | null | 自定义 logger |
总结
通过使用 @wf-cms/egg-cms-database,我们可以方便地管理数据库,并且拓展了 egg-cms 框架的功能。希望本文对于前端开发人员有所帮助,欢迎大家提出宝贵意见。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/600672673660cf7123b365c2