ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] > [github](https://github.com/sequelize/sequelize) ## 安装 ``` $ npm install --save sequelize # 添加需要的 引擎 $ npm install --save pg pg-hstore $ npm install --save mysql2 $ npm install --save mariadb $ npm install --save sqlite3 $ npm install --save tedious # MSSQL ``` ## 基础使用 ``` const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql'|'sqlite'|'postgres'|'mssql', pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, ## 应用全局的模型参数 define: { freezeTableName: false, //取消自动表加s charset: 'utf8', dialectOptions: { collate: 'utf8_general_ci' }, timestamps: false, //不添加时间戳属性 (updatedAt, createdAt) paranoid: true,//伪删除 ,deletedAt必须设置, 前提开启timestamps }, }); //创建模型 const User = sequelize.define('user', { firstName: { type: Sequelize.STRING }, lastName: { type: Sequelize.STRING } }); // force: true 如果表已经存在,将会丢弃表 User.sync({force: true}).then(() => { // 表已创建 return User.create({ firstName: 'John', lastName: 'Hancock' }); }); ``` ``` const sequelize = new Sequelize('connectionUri', { define: { timestamps: false // 默认为 true } }); ``` ## 模型定义 ``` { primaryKey: true, // type: Sequelize.STRING, //DATE BOOLEAN INTEGER allowNull: false, someUnique: {type: Sequelize.STRING, unique: true}, autoIncrement: true } //自动插入时间戳 myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW } ``` ### Getters & setters ``` /* 一个用于 'title' 属性的 getter */ get() { return this.getDataValue('title') } set(title) { this.setDataValue('title', title.toString().toLowerCase()); } ```` ### 验证 `create` , `update` 和 `save` 上。 你也可以调用 validate() 手动验证一个实例 ``` const ValidateMe = sequelize.define('foo', { foo: { type: Sequelize.STRING, validate: { is: ["^[a-z]+$",'i'], // 只允许字母 is: /^[a-z]+$/i, // 与上一个示例相同,使用了真正的正则表达式 not: ["[a-z]",'i'], // 不允许字母 isEmail: true, // 检查邮件格式 (foo@bar.com) isEven(value) { if (parseInt(value) % 2 != 0) { throw new Error('Only even values are allowed!') // 我们也在模型的上下文中,所以如果它存在的话, // this.otherField会得到otherField的值。 } } }}); ``` ## 增删改查 ### 查 查询特定字段 ``` Model.findAll({ attributes: ['foo', 'bar'] }); ``` 重命名 ``` Model.findAll({ attributes: ['foo', ['bar', 'baz']] }); ``` 聚合 ``` Model.findAll({ attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] }); ``` where ``` Post.findAll({ where: { authorId: 2 } }); Post.findAll({ where: { [Op.or]: [{authorId: 12}, {authorId: 13}] } }); // SELECT * FROM post WHERE authorId = 12 OR authorId = 13; Post.findAll({ where: { authorId: { [Op.or]: [12, 13] } } }); ``` ## 更新 ``` Post.update({ updatedAt: null, }, { where: { deletedAt: { [Op.ne]: null } } }); ``` 操作符 ``` const Op = Sequelize.Op [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) ``` ## 分页 / 限制 ``` // 获取10个实例/行 Project.findAll({ limit: 10 }) // 跳过8个实例/行 Project.findAll({ offset: 8 }) // 跳过5个实例,然后取5个 Project.findAll({ offset: 5, limit: 5 }) ``` ## 一对一关联 ``` const Player = this.sequelize.define('player', {/* attributes */}); const Team = this.sequelize.define('team', {/* attributes */}); Player.belongsTo(Team); // 将向 Player 添加一个 teamId 属性以保存 Team 的主键值 ```