sequelize
1、安装
npm install --save egg-sequelize mysql2
npm install --save-dev sequelize-cli
2、config目录下设置配置文件
plugin.js(修改)
exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
config.sequelize.js(创建)
'use strict';
const sequelize = {
dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
database: '数据库名',
host: 'localhost',
port: '3306',
username: 'root',
password: '123456',
define: { // model的全局配置
timestamps: true, // 添加create,update,delete时间戳
paranoid: true, // 添加软删除
freezeTableName: true, // 防止修改表名为复数
underscored: false // 防止驼峰式字段被默认转为下划线
},
timezone: '+8:00', // 由于orm用的UTC时间,这里必须加上东八区,否则取出来的时间相差8小时
dialectOptions: { // 让读取date类型数据时返回字符串而不是UTC时间
dateStrings: true,
typeCast(field, next) {
if (field.type === "DATETIME") {
return field.string();
}
return next();
}
}
};
module.exports = sequelize;
3、引用配置文件
config.default.js
/* eslint valid-jsdoc: "off" */
'use strict';
const sequelizeConfig = require('./config.sequelize');
module.exports = appInfo => {
...
config.sequelize = sequelizeConfig//数据库
return {
...config,
...userConfig,
};
};
4、指定sequelize文件位置
项目根目录下创建.sequelizerc 配置文件
.sequelizerc
'use strict';
const path = require('path');
module.exports = {
config: path.join(__dirname, 'database/config.json'),
'migrations-path': path.join(__dirname, 'database/migrations'),
'seeders-path': path.join(__dirname, 'database/seeders'),
'models-path': path.join(__dirname, 'app/model'),
};
5、生成初始化文件
npx sequelize init:config
npx sequelize init:migrations
或者直接
npx sequelize init
执行完后会生成 database/config.json 文件和 database/migrations 目录,我们修改一下 database/config.json 中的内容,将其改成我们项目中使用的数据库配置
config.json
{
"dev": {
"username": "root",
"password": "123456",
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": "123456",
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": "123456",
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
6、生成一个 migration 文件
命令行:
npx sequelize migration:generate --name=init-users
6、生成一个 model 文件和 migration 文件
npx sequelize models:create --name <表名> --attributes “列1:类型[, 列2:类型, …]”
命令行:
npx sequelize model:generate --name=user --attributes "uid:INTEGER"
7、创建数据库
npx sequelize db:create --env=环境
npx sequelize db:create --env=dev
npx sequelize db:create --charset ‘字符编码’ --env=环境
npx sequelize db:create --charset ‘utf8mb4’ --env=环境
8、将migration 文件生成表
npx sequelize db:migrate
egg配置自动生成数据库表https://blog.csdn.net/weixin_30621711/article/details/97224302
中文文档数据类型页https://itbilu.com/nodejs/npm/V1PExztfb.html#definition-dataType
中文文档数据类型页https://www.sequelize.com.cn/other-topics/other-data-types
egg启动dev正常,start错误
egg-scripts start --port=7001 --daemon --title=egg-manage --ignore-stderr