创建连接
const { Sequelize } = require('sequelize');// 第一个参数:连接的数据库名
// 第二个参数:数据库的用户名
// 第三个参数:数据库的密码
const mysql = new Sequelize('mytest', 'root', 'root', {dialect: 'mysql', // 这里可以改成任意一种关系型数据库host: 'localhost', // 数据库服务器timezone: '+08:00', // 这里是东八区,默认为0时区pool: { // 使用连接池max: 5,min: 0,acquire: 30000,idle: 10000,},
});
测试连接
// 测试连接是否成功
(async () => {try {await mysql.authenticate();console.log('Connection has been established successfully.');} catch (error) {console.error('Unable to connect to the database:', error);}
})(); // 多一个括号表示调用方法
完整db定义类
const AppConfig = {environment: "dev",database: {database: "notes_app", // 库名username: "notes_app", // 用户名password: "notes_app", // 密码options: {// 配置host: "localhost",dialect: "mysql",define: {// create_time && update_timetimestamps: true,// delete_timeparanoid: true,createdAt: "created_at",updatedAt: "updated_at",deletedAt: "deleted_at",// 把驼峰命名转换为下划线underscored: true,scopes: {bh: {attributes: {exclude: ["updated_at", "deleted_at", "created_at"]}},iv: {attributes: {exclude: ["updated_at", "deleted_at"]}}}},pool: {max: 5,min: 0,acquire: 30000,idle: 10000},timezone: "+08:00" // 东八时区}},security: {secretKey: "secretKey",// 过期时间 1小时expiresIn: 60 * 60}
};module.exports = AppConfig;
const { Sequelize } = require("sequelize");const AppConfig = require("../config/config");class DbManager {constructor() {this.config = AppConfig.database;this.sequelize = null;this.isConnected = false;}async isConnection() {const { database, username, password, options } = this.config;this.sequelize = new Sequelize(database, username, password, options);try {await this.sequelize.authenticate();// console.log("successfully");this.isInitOk = true;return true;} catch (error) {console.error("Unable to connect to the database:", error);return false;}}start() {const isConnected = this.isConnection();this.isConnected = isConnected;if (isConnected) {// console.log("连接ok");return true;}}stop() {if (this.sequelize !== null) {this.sequelize.close();console.log("连接close");}}getSequelize() {return this.sequelize;}getIsConnected() {return this.isConnected;}
}const dbManager = new DbManager();
dbManager.start();const sequelize = dbManager.getSequelize();
// console.log(sequelize);
sequelize.sync({ force: false }); // 初始化模型module.exports = {dbManager,sequelize
};
常用DataTypes定义
Sequelize.STRING // VARCHAR(255)
Sequelize.STRING(1234) // VARCHAR(1234)
Sequelize.STRING.BINARY // VARCHAR BINARY
Sequelize.TEXT // TEXT
Sequelize.TEXT('tiny') // TINYTEXTSequelize.INTEGER // INTEGER
Sequelize.BIGINT // BIGINT
Sequelize.BIGINT(11) // BIGINT(11)Sequelize.FLOAT // FLOAT
Sequelize.FLOAT(11) // FLOAT(11)
Sequelize.FLOAT(11, 12) // FLOAT(11,12)Sequelize.REAL // REAL 仅限于PostgreSQL.
Sequelize.REAL(11) // REAL(11) 仅限于PostgreSQL.
Sequelize.REAL(11, 12) // REAL(11,12) 仅限于PostgreSQL.Sequelize.DOUBLE // DOUBLE
Sequelize.DOUBLE(11) // DOUBLE(11)
Sequelize.DOUBLE(11, 12) // DOUBLE(11,12)Sequelize.DECIMAL // DECIMAL
Sequelize.DECIMAL(10, 2) // DECIMAL(10,2)Sequelize.DATE // DATETIME 针对 mysql / sqlite, TIMESTAMP WITH TIME ZONE 针对 postgres
Sequelize.DATE(6) // DATETIME(6) 针对 mysql 5.6.4+. 小数秒支持多达6位精度
Sequelize.DATEONLY // DATE 不带时间.
Sequelize.BOOLEAN // TINYINT(1)Sequelize.ENUM('value 1', 'value 2') // 一个允许具有 “value 1” 和 “value 2” 的 ENUM
Sequelize.ARRAY(Sequelize.TEXT) // 定义一个数组。 仅限于 PostgreSQL。
Sequelize.ARRAY(Sequelize.ENUM) // 定义一个 ENUM 数组. 仅限于 PostgreSQL。
添加model
const { Model, DataTypes } = require("sequelize");
const { sequelize } = require("../util/db");class Cate extends Model {}Cate.init({id: {type: DataTypes.INTEGER,primaryKey: true, // 主键autoIncrement: true // 自增},uid: {type: DataTypes.UUID,defaultValue: DataTypes.UUIDV4,unique: true // 唯一},name: DataTypes.STRING,icon: DataTypes.STRING,desc: DataTypes.TEXT,parentUid: DataTypes.UUID},{sequelize,tableName: "cate" // 指定生成的表名}
);module.exports = {Cate
};
为model添加初始
Cate.sync({ force: false }).then(async () => {await Cate.create({name: "所有笔记",icon: "<IconFolder />",desc: "所有笔记",parentUid: ""});await Cate.create({name: "标签",icon: "<IconTags />",desc: "标签",parentUid: ""});await Cate.create({name: "回收站",icon: "<IconDelete />",desc: "回收站",parentUid: ""});}).catch(err => {console.log("err= ", err);}); // 初始化模型
模型关联
一对一
文章
class Article extends Model {}Article.init({id: {type: DataTypes.INTEGER,primaryKey: true, // 主键autoIncrement: true // 自增},uid: {type: DataTypes.UUID,primaryKey: true, // 主键defaultValue: DataTypes.UUIDV4},title: DataTypes.STRING,deleteUid: DataTypes.UUID,collectUid: DataTypes.UUID,publishStatus: {type: DataTypes.INTEGER,// (0草稿、1公开、2私有)defaultValue: 0}},{sequelize,tableName: "article" // 指定生成的表名}
);
文章内容
class ArticleContent extends Model {}ArticleContent.init({id: {type: DataTypes.INTEGER,primaryKey: true, // 主键autoIncrement: true // 自增},uid: {type: DataTypes.UUID,primaryKey: true, // 主键defaultValue: DataTypes.UUIDV4},content: DataTypes.TEXT},{sequelize,timestamps: false,tableName: "article_content" // 指定生成的表名}
);
关联关系定义
// 关联意味着 A 和 B 之间存在一对一的关系,外键在目标模型(B)中定义.
ArticleContent.hasOne(Article, {foreignKey: "article_content_uid",sourceKey: "uid"
});// A.belongsTo(B)关联意味着 A 和 B 之间存在一对一的关系,外键在源模型中定义(A).
Article.belongsTo(ArticleContent, {foreignKey: "article_content_uid",sourceKey: "uid"
});
多对多
分类
class Cate extends Model {}
Cate.init({id: {type: DataTypes.INTEGER,primaryKey: true, // 主键autoIncrement: true // 自增},uid: {type: DataTypes.UUID,primaryKey: true, // 主键defaultValue: DataTypes.UUIDV4},name: DataTypes.STRING,icon: DataTypes.STRING,desc: DataTypes.TEXT,parentUid: DataTypes.UUID},{sequelize,tableName: "cate" // 指定生成的表名}
);
文章分类关联表定义
class ArticleCates extends Model {}ArticleCates.init({id: {type: DataTypes.INTEGER,primaryKey: true, // 主键allowNull: false,autoIncrement: true // 自增},uid: {type: DataTypes.UUID,primaryKey: true, // 主键defaultValue: DataTypes.UUIDV4}},{sequelize,timestamps: false,tableName: "articale_cates" // 指定生成的表名}
);
关联关系定义(采用两个一对多的方式)
Article.hasMany(ArticleCates, {foreignKey: "article_uid",sourceKey: "uid"
});Cate.hasMany(ArticleCates, {foreignKey: "cate_uid",sourceKey: "uid"
});ArticleCates.belongsTo(Article, { foreignKey: "article_uid" });
ArticleCates.belongsTo(Cate, { foreignKey: "cate_uid" });
生成的关联表
如果采用多对多方式关联,始终都关联不上uid,可以用id关联。
Article.belongsToMany(Cate, {through: ArticleCates,foreignKey: "article_uid", // ArticleCates 表中表示文章 uid 的字段名sourceKey: "uid",otherKey: "cate_uid" // ArticleCates 表中表示分类 uid 的字段名
});
Cate.belongsToMany(Article, {through: ArticleCates,foreignKey: "cate_uid", // ArticleCates 表中表示分类 uid 的字段名sourceKey: "uid",otherKey: "article_uid" // ArticleCates 表中表示文章 uid 的字段名
});