https://sequelize.org/v5/manual/getting-started.html sequelize官方文档
https://sequelize.org/v5/class/lib/model.js~Model.html api
$ npm install —save sequelize
$ npm install —save pg pg-hstore # Postgres
$ npm install —save mysql2
$ npm install —save mariadb
$ npm install —save sqlite3
$ npm install —save tedious # Microsoft SQL Server
const Sequelize = require('sequelize');const sequelize = new Sequelize('database', 'username', 'password', {host: 'url',port: 3306,dialect: 'mysql' // 数据库类型})sequelize.authenticate().then(() => {console.log('Connection has been established successfully.');const Model = Sequelize.Model;class TestUser extends Model {}TestUser.init({xxxId: {type: Sequelize.INTEGER,// 设置为 false 表示 not nullallowNull: false,field: 'roleId',unique: true,primaryKey: true, // 设置了主键,就不会自动增加id了autoIncrement: true, // 自增列},// attributesfirstName: {type: Sequelize.STRING,allowNull: false},lastName: {type: Sequelize.STRING// allowNull defaults to true}}, {// 自增列,开始值initialAutoIncrement: 10000,sequelize,modelName: 'test_user',// options/** 表名称 */tableName: 'test_user',// 此属性约定是否自动创建,createdAt与updatedAttimestamps: false});// force: true 这沙雕参数会删表TestUser.sync({}).then(() => { // 创建表}).then(()=>{return TestUser.findAll().then(users => {console.log("All users:", JSON.stringify(users, null, 4));});}).then(()=>{sequelize.close();})// // Create a new user// User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => {// console.log("Jane's auto-generated ID:", jane.id);// });// // Delete everyone named "Jane"// User.destroy({// where: {// firstName: "Jane"// }// }).then(() => {// console.log("Done");// });// // Change everyone without a last name to "Doe"// User.update({ lastName: "Doe" }, {// where: {// lastName: null// }// }).then(() => {// console.log("Done");// });// sequelize.close();}).catch(err => {console.error('Unable to connect to the database:', err);});/*注意:设置SQLite如果您使用的是SQLite,则应改用以下内容:const sequelize = new Sequelize({dialect: 'sqlite',storage: 'path/to/database.sqlite'});注意:连接池(生产)如果要从单个进程连接到数据库,则应仅创建一个Sequelize实例。Sequelize将在初始化时建立连接池。可以通过构造函数的options参数(使用options.pool)来配置此连接池,如以下示例所示:const sequelize = new Sequelize( ... , {// ...pool: {max: 5,min: 0,acquire: 30000,idle: 10000}});*/
const {Op} = Sequelize;await XXXModel.update({status: '1'}, {where: {status: {[Op.in]: ['2', '3', '4', '5']}}});[Op.and]: {a: 5} // 且 (a = 5)[Op.or]: [{a: 5}, {a: 6}] // (a = 5 或 a = 6)[Op.gt]: 6, // id > 6[Op.gte]: 6, // id >= 6[Op.lt]: 10, // id < 10[Op.lte]: 10, // id <= 10[Op.ne]: 20, // id != 20[Op.eq]: 3, // = 3[Op.not]: true, // 不是 TRUE[Op.between]: [6, 10], // 在 6 和 10 之间[Op.notBetween]: [11, 15], // 不在 11 和 15 之间[Op.in]: [1, 2], // 在 [1, 2] 之中[Op.notIn]: [1, 2], // 不在 [1, 2] 之中[Op.like]: '%hat', // 包含 '%hat'[Op.notLike]: '%hat' // 不包含 '%hat'[Op.iLike]: '%hat' // 包含 '%hat' (不区分大小写) (仅限 PG)[Op.notILike]: '%hat' // 不包含 '%hat' (仅限 PG)[Op.regexp]: '^[h|a|t]' // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)[Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)[Op.iRegexp]: '^[h|a|t]' // ~* '^[h|a|t]' (仅限 PG)[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)[Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 同样适用于 iLike 和 notLike[Op.overlap]: [1, 2] // && [1, 2] (PG数组重叠运算符)[Op.contains]: [1, 2] // @> [1, 2] (PG数组包含运算符)[Op.contained]: [1, 2] // <@ [1, 2] (PG数组包含于运算符)[Op.any]: [2,3] // 任何数组[2, 3]::INTEGER (仅限PG)[Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG
CreateAt:创建时间UpdateAt:更新时间DeleteAt:被删除时间CreateBy:创建人UpdateBy:更新人IsDelete:伪删除字段CreateAt:bigintUpdateAt:bigintDeleteAt:bigintCreateBy:varcharUpdateBy:varcharIsDelete:tinyint
例子
/** model/config/default.js */const Sequelize = require('sequelize');module.exports = {createdBy: {type: Sequelize.STRING,allowNull: false,field: 'created_by',},updatedBy: {type: Sequelize.STRING,field: 'updated_by'},deletedBy: {type: Sequelize.STRING,field: 'deleted_by'},createdAt: {type: Sequelize.DATE,allowNull: false,field: 'created_at'// allowNull defaults to true},updatedAt: {type: Sequelize.DATE,field: 'updated_at'// allowNull defaults to true},/** 删除时间 */deletedAt: {type: Sequelize.DATE,field: 'deleted_at'},/** 伪删除字段 伪删除字段 1 表示删除 */isDelete: {type: Sequelize.TINYINT,field: 'is_delete',defaultValue: 0}}
/** model/application.js */const Sequelize = require('sequelize');const defaultInit = require('./config/default')const Model = Sequelize.Model;const { Op } = Sequelize;class Application extends Model { }module.exports = async (sequelize) => {Application.init({// attributesappName: {type: Sequelize.STRING,// 设置为 false 表示 not nullallowNull: false,field: 'app_name',unique: true,},...defaultInit}, {sequelize,/** 表名称 */tableName: 'application_list',/** 模型名称 */modelName: 'application_list',// options// 此属性约定是否自动创建,createdAt与updatedAttimestamps: false});return Application.sync({ force: true }).then(() => {return {destroy (appNames) {return Application.destroy({ where: { appName: { [Op.in]: appNames } } }).then(res => {if (Array.isArray(res) && res.length) {return true}return false});},delete (appNames) {const deletedAt = new Date()return Application.update({deletedAt: deletedAt,isDelete: 1}, { where: { appName: { [Op.in]: appNames } }, }).then(res => {// console.log(res) [ 0 ] 默认会返回这个if (Array.isArray(res) && res.length) {return true}return false})},getOne (appName) {return Application.findAll({where: {appName,isDelete: { [Op.ne]: 1 }},}).then(res => {return res[0]})},getAll () {return Application.findAll({ where: { isDelete: { [Op.ne]: 1 } } })},create ({appName,createdBy,updatedBy,createdAt,updatedAt}) {return Application.create({appName,createdBy,updatedBy,createdAt,updatedAt})}}})}
/** model/index.js */const ApplicationInit = require('./application')module.exports = async (sequelize) => {const model = {}model.application = await ApplicationInit(sequelize)return model}
if (data.length === 0) { // 初始化数据const createdBy = new Date()await Permissions.bulkCreate([{ruleId: 10000,ruleType: 'operator_rule', // 操作功能权限createdBy: '__system',createdAt: createdBy},{ruleId: 10001,ruleType: 'menu_rule', // 菜单权限createdBy: '__system',createdAt: createdBy},{ruleId: 10002,ruleType: 'page_item_rule', // 页面元素权限createdBy: '__system',createdAt: createdBy},{ruleId: 10003,ruleType: 'file_rule', // 文件权限createdBy: '__system',createdAt: createdBy}])}
事务
// 创建事务sequelize.transaction(function (t) {// 在事务中执行操作return User.create({username: 'itbilu.com', password: 'pwd', active: true}, {transaction:t}).then(function(user){return UserCheckin.create({userId: user.id, loginIp:'localhost'}, {transaction:t})});}).then(function (results){/* 操作成功,事务会自动提交 */}).catch(function(err){/* 操作失败,事件会自动回滚 */});return sequelize.transaction(function (t) {// 一些在事务中进行的操作}).then(function (result) {// Transaction 会自动提交// result 是事务回调中使用promise链中执行结果}).catch(function (err) {// Transaction 会自动回滚// err 是事务回调中使用promise链中的异常结果});// 启动一个不受管理的事务return sequelize.transaction().then(function (t) {// 一些在事务中进行的操作return User.create({firstName: 'Homer',lastName: 'Simpson'}, {transaction: t}).then(function (user) {return user.addSibling({firstName: 'Lisa',lastName: 'Simpson'}, {transaction: t});}).then(function () {// 手工提交事务return t.commit();}).catch(function (err) {// 手工回滚事务return t.rollback();});});
