此模块是一个广泛使用的 ORM 框架,它支持 MySQL、PostgreSQL、SQLite 和 MSSQL 等多个数据源。
先安装
npm install --save egg-sequelize
在 config/plugin.js 中引入 egg-sequelize 插件
sequelize: {
enable: true,
package: 'egg-sequelize',
};
在 config/config.default.js 中编写 sequelize 配置
config.sequelize = {
dialect: 'mysql',
database: 'xxxx', //你的数据库名称
username: 'xxxx', // 你的数据库帐号
password: 'xxxx', //你的数据库密码
host: 'localhost',
port: '3306',
define: {
// 使用自定义的表名
freezeTableName: true,
// 自动生成时间戳 -小驼峰式
timestamps: true,
// 表名小驼峰
underscored: false,
},
};
在app目录下创建一个名为model的目录
再创建一个js比如:userConfig.js
创建一个表名为 users 内容如下
'use strict';
module.exports = (app) => {
const { STRING, INTEGER, DATE, BIGINT, TEXT } = app.Sequelize; // 获取数据类型
// AI小程序分享、看视频、增加次数记录
const User = app.model.define(
'users',
{
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
username: { type: STRING }, // 名字
password: { type: STRING }, // 密码
openid: { type: STRING },
type: { type: STRING, allowNull: false, defaultValue: 1 }, // 1 普通用户 2 管理员
add_time: { type: BIGINT, allowNull: false }, // 注册时间
},
{
freezeTableName: true, // Model 对应的表名将与model名相同
timestamps: false,
paranoid: true, //是否创建删除字段(逻辑删除)
version: true,
}
);
return User;
};
// 下面为各个方法的具体介绍
/*
defaultValue 设置默认 Boolean
allowNull 是否允许为空 Boolean
unique 属性用来创建一个唯一约束. Boolean | string
primaryKey 用于定义主键. Boolean
autoIncrement 可用于创建自增的整数列 Boolean
comment 注释 string;
references: {
// 这是引用另一个模型
model: Bar,
// 这是引用模型的列名称
key: 'id',
// 这声明什么时候检查外键约束. 仅限PostgreSQL.
deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
}
*/
最后一步把下部分代码放在router.js里,可以启动项目的时候自动创建定义的表
app.beforeStart(async () => {
await app.model.sync({
alter: true
}); //force false 为不覆盖 true会删除再创建; alter true可以 添加或删除字段;
});