Sequelize 是 Node 的一个 ORM(Object-Relational Mapping) 框架,用来方便数据库操作。
配置 sequelize
以 mysql 为例
首先我们要引入npm包,sequelize 依赖 mysql2 作为底层驱动,暴露出自己的 API 让我们调用,在转成 mysql 语句进行执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | "mysql2" : "^1.5.1" , "sequelize" : "^4.28.6" const Sequelize = require( 'sequelize' ) // 连接数据库 const sequelize = new Sequelize( 'database' , 'username' , 'password' , { host: sqlconf.host, dialect: 'mysql' , // 这里可以改成任意一种关系型数据库 pool: { max: 5, min: 0, acquire: 30000, idle: 10000, }, }) // 测试连接是否成功 sequelize .authenticate() .then(() => { console.log( 'Connection has been established successfully.' ) }) . catch (err => { console.log( 'Unable to connect to the database' , err) }) // 根据 model自动创建表 sequelize .sync() .then(() => { console.log( 'init db ok' ) }) . catch (err => { console.log( 'init db error' , err) }) |
我们可以调用sync()
根据 model自动在数据库中创建表,也可以不调用,自己手动创。如果使用了 Sequelize 的 Associations,这必须通过 sync()
生成表结构。
创建 model
创建模型,告诉 Sequelize 如何映射数据库表
1 2 3 4 5 6 7 8 9 10 11 12 13 | const UserModel = sequelize.define( 'user' , { id: { type: Sequelize.INTEGER(11), primaryKey: true , // 主键 autoIncrement: true , // 自动递增 }, username: Sequelize.STRING(100), password: Sequelize.STRING(100), createdAt: Sequelize.BIGINT, updatedAt: Sequelize.BIGINT, }, { timestamps: false }) |
define()
方法的第一个参数为表名,对应的是 users 表。如果不设置 timestamps,Sequlize 会自动为我们添加创建时间和更新时间,我一般选择关闭,手动添加灵活性高些。
增删改查
增
1 2 3 4 5 6 7 8 9 10 | (async () => { const now = Date.now() const user = await UserModel.create({ username: '小张' , password: 'root' , createAt: now, updateAt: now, }) console.log( '创建:' + JSON.stringify(user)) })(); |
查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | (async () => { // 查找所有 const allUser = await UserModel.findAll() // 按id查找 const oneUser = await UserModel.findById(id) // 按条件查询 const someUser = await UserModel.findAll({ where : { // 模糊查询 name: { $like: '%小%' , }, // 精确查询 password: 'root' , } }) // 分页查询 const size = 10 // 每页10条数据 const page = 1 // 页数 const pageUser = await UserModel.findAndCountAll({ where : { name: { $like: '%小%' , }, }, limit: size, offset: size * (page - 1), }) })(); |
改
1 2 3 4 5 6 7 8 | (async () => { // 方法一 await UserModel.upert(data) // data 里面如果带有 id 则更新,不带则新建 // 方法二 const user = await UserModel.findById(id) user.update(data) })() |
删
1 2 3 4 5 6 7 8 9 10 11 12 13 | (async () => { // 方法一 // 删除所有名字带’小‘的用户 await UserModel.destroy({ where : { username: '小' , }, }) // 方法二 const user = await UserModel.findById(id) user.destroy() })() |
操作符
别名对照(左边为别名)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | const operatorsAliases = { $eq: Op.eq, $ne: Op.ne, $gte: Op.gte, $gt: Op.gt, $lte: Op.lte, $lt: Op.lt, $not: Op.not, $ in : Op. in , $notIn: Op.notIn, $ is : Op. is , $like: Op.like, $notLike: Op.notLike, $iLike: Op.iLike, $notILike: Op.notILike, $regexp: Op.regexp, $notRegexp: Op.notRegexp, $iRegexp: Op.iRegexp, $notIRegexp: Op.notIRegexp, $between: Op.between, $notBetween: Op.notBetween, $overlap: Op.overlap, $contains: Op.contains, $contained: Op.contained, $adjacent: Op.adjacent, $strictLeft: Op.strictLeft, $strictRight: Op.strictRight, $noExtendRight: Op.noExtendRight, $noExtendLeft: Op.noExtendLeft, $and: Op.and, $or: Op.or, $any: Op.any, $all: Op.all, $values: Op.values, $col: Op.col }; |
原始解释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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) [Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG |
sequelize 数据类型 model
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗