我的GitHub
0%

无星的Egg之旅(三)——sequelize

sequelize引入

1
2
npm i mysql2
npm i egg-sequelize

sequelize配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 不同环境的库当然不一样,自己配置多环境的config.xx.js,我这就写个default
// ./config/config.default.js
// sql配置,填自己的即可
config.sequelize = {
dialect: 'mysql',
host: '127.0.0.1',
port: 3306,
database: 'monitor',
username: 'root',
password: '123456',
define: { // model的全局配置
timestamps: true, // 添加create,update,delete时间戳
paranoid: true, // 添加软删除
freezeTableName: true, // 防止修改表名为复数
underscored: true, // 使用下划线
},
timezone: '+8:00', // 由于orm用的UTC时间,这里必须加上东八区,否则取出来的时间相差8小时
dialectOptions: { // 让读取date类型数据时返回字符串而不是UTC时间
dateStrings: true,
typeCast(field, next) {
if (field.type === 'DATETIME') {
return field.string();
}
return next();
},
},
};

插件配置

开启sequelize插件

./config/plugin.js

1
2
3
4
5
6
7
8
9
10
11
12
'use strict';


/** @type Egg.EggPlugin */
module.exports = {
// xxxxxx
sequelize: {
enable: true,
package: 'egg-sequelize',
},
};

用法

和正常的sequelize相似

新建一个model文件夹

新建model

例如,我新建一个叫project的model

定义model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//在插件开启plugin以后,Sequelize会被挂载到app上
const { STRING, DATE } = app.Sequelize;
// 通过app.model.define方式新建
const Project = app.model.define('project', {
app_id: {
type: STRING,
primaryKey: true,
},
app_name: STRING(30),
jenkins_name: STRING,
map_source: STRING,
git_url: STRING,
created_at: DATE,
updated_at: DATE,
});

定义方法增删改查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//定义一个方法,叫createByAppId

Project.createByAppId = async function({ appId,
appName,
jenkinsName,
mapSource,
gitUrl }) {

// create是sequelize的方法,具体可以查看sequelize文档

return await this.create({
app_id: appId,
app_name: appName,
jenkins_name: jenkinsName,
map_source: mapSource,
git_url: gitUrl,
});
};

调用

1
2
// 其他js调用这个createByAppId
const tmp = await this.ctx.model.Project.createByAppId({xxxx});

project.js全貌如下

/model/project.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';

module.exports = app => {
const { STRING, DATE } = app.Sequelize;

const Project = app.model.define('project', {
app_id: {
type: STRING,
primaryKey: true,
},
app_name: STRING(30),
jenkins_name: STRING,
map_source: STRING,
git_url: STRING,
created_at: DATE,
updated_at: DATE,
});
//增
Project.createByAppId = async function({ appId,
appName,
jenkinsName,
mapSource,
gitUrl }) {
return await this.create({
app_id: appId,
app_name: appName,
jenkins_name: jenkinsName,
map_source: mapSource,
git_url: gitUrl,
});
};
//查
Project.findByAppId = async function(appid) {
return await this.findOne({
where: {
appid,
},
});
};

// 改
Project.prototype.logSignin = async function() {
return await this.update({ last_sign_in_at: new Date() });
};

return Project;
};

我是阿星,阿星的阿,阿星的星!