您现在的位置是:网站首页> 编程资料编程资料

Nodejs Sequelize手册学习快速入门到应用_node.js_

2023-05-24 454人已围观

简介 Nodejs Sequelize手册学习快速入门到应用_node.js_

1.连接数据库(js/ts)

 // config.js exports const config = { database: { database: 'management', host: 'localhost', port: 3306, user: 'root', password: '12345678' } } 
 // db.js const Sequelize = require('sequelize'); import { config } from './config'; const { database, host, port, user, password } = config; const sequelize = new Sequelize(database, user, password, { dialect: 'mysql', host, port, logging: true, // logging: true, 打印sql到控制台 timezone: '+08:00', //时间上的统一,这里是东八区,默认为0时区 define: { //全局的定义,会通过连接实例传递 // timestamps: false, //默认情况下,Sequelize 使用数据类型 DataTypes.DATE 自动向每个模 型添加 createdAt 和 updatedAt 字段. 这些字段会自动进行管理 - 每当 你使用Sequelize 创建或更新内容时,这些字段都会被自动设置. createdAt 字段将包含代表创建时刻的时间戳,而 updatedAt 字段将包含 最新更新的时间戳. //对于带有timestamps: false 参数的模型,可以禁用此行为 // createdAt: 'created_at', //自定义时间戳 // updatedAt: 'updated_at', // paranoid: true, // deletedAt: 'deleted_at', //paranoid表示在被告之要删除记录时并不会真正的物理上删除,而 是添加一个存有删除请求时间戳deletedAt的特殊字段。传递 paranoid: true参数给模型定义中。paranoid要求必须启用时间戳, 即必须传timestamps: true // 把驼峰命名转换为下划线 //underscored: false, pool: { // 使用连接池 max: 5, // 连接池中最大连接数量 min: 0, // 连接池中最小连接数量 acquire: 30000, idle: 10000 // 如果一个线程 10 秒钟内没有被使用过的话,那么就释放线程 }, } }) // 测试数据库链接 sequelize .authenticate() .then(() => { console.log('数据库连接成功'); }) .catch((err: any) => { // 数据库连接失败时打印输出 console.error(err); throw err; }); export default sequelize; // 将连接对象暴露出去 

2.数据库模型

1.模型定义

调用sequelize.define(modelName, attributes, options)

 const User = sequelize.define('User', { // 在这里定义模型属性 id: { type: DataTypes.INTEGER, autoIncrement: true, //允许自增 primaryKey: true } firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING // allowNull 默认为 true } }, { // 这是其他模型参数 sequelize, // 我们需要传递连接实例 //局部的定义 modelName: 'User' // 我们需要选择模型名称 // 不要忘记启用时间戳! timestamps: true, // 不想要 createdAt createdAt: false, // 想要 updatedAt 但是希望名称叫做 updateTimestamp updatedAt: 'updateTimestamp' }); // `sequelize.define` 会返回模型 console.log(User === sequelize.models.User); // true 

时间戳(timestamps)

默认情况下,Sequelize 使用数据类型 DataTypes.DATE 自动向每个模型添加 createdAtupdatedAt 字段. 这些字段会自动进行管理 - 每当你使用Sequelize 创建或更新内容时,这些字段都会被自动设置. createdAt 字段将包含代表创建时刻的时间戳,而 updatedAt 字段将包含最新更新的时间戳.

对于带有 timestamps: false 参数的模型,可以禁用此行为,要启用createdAt,updatedAt必须要 timestamps: true

 sequelize.define('User', { // ... (属性) }, { timestamps: false }); 

也可以只启用 createdAt/updatedAt 之一,并为这些列提供自定义名称:

 class Foo extends Model {} Foo.init({ /* 属性 */ }, { sequelize, // 不要忘记启用时间戳! timestamps: true, // 不想要 createdAt createdAt: false, // 想要 updatedAt 但是希望名称叫做 updateTimestamp updatedAt: 'updateTimestamp' }); 

2.生成模型

1.全局安装sequelize-automysql2

 npm install -g mysql2 npm install -g sequelize-auto 

2. 运行以下命令

利用sequelize-auto对照数据库自动生成相应的models,sequelize-auto官方文档地址:github.com/sequelize/s…

 //sequelize-auto -h "数据库地址" -d "数据库名" -u "用户名" -x "密码" -p "端口号" --dialect mysql sequelize-auto -o "./model" -d test -h 127.0.0.1 -u root -p 3306 -x 123456 -e mysql Options: --help Show help [boolean] --version Show version number [boolean] -h, --host IP/Hostname for the database. [string] -d, --database Database name. [string] -u, --user Username for database. [string] -x, --pass Password for database. If specified without providing a password, it will be requested interactively from the terminal. -p, --port Port number for database (not for sqlite). Ex: MySQL/MariaDB: 3306, Postgres: 5432, MSSQL: 1433 [number] -c, --config Path to JSON file for Sequelize-Auto options and Sequelize's constructor "options" flag object as defined here: https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor [string] -o, --output What directory to place the models. [string] -e, --dialect The dialect/engine that you're using: postgres, mysql, sqlite, mssql [string] -a, --additional Path to JSON file containing model options (for all tables). See the options: https://sequelize.org/master/class/lib/model.js~Model.html#static-method- init [string] --indentation Number of spaces to indent [number] -t, --tables Space-separated names of tables to import [array] -T, --skipTables Space-separated names of tables to skip [array] --caseModel, --cm Set case of model names: c|l|o|p|u c = camelCase l = lower_case o = original (default) p = PascalCase u = UPPER_CASE --caseProp, --cp Set case of property names: c|l|o|p|u --caseFile, --cf Set case of file names: c|l|o|p|u|k k = kebab-case --noAlias Avoid creating alias `as` property in relations [boolean] --noInitModels Prevent writing the init-models file [boolean] -n, --noWrite Prevent writing the models to disk [boolean] -s, --schema Database schema from which to retrieve tables[string] -v, --views Include database views in generated models [boolean] -l, --lang Language for Model output: es5|es6|esm|ts es5 = ES5 CJS modules (default) es6 = ES6 CJS modules esm = ES6 ESM modules ts = TypeScript [string] --useDefine Use `sequelize.define` instead of `init` for es6|esm|ts --singularize, --sg Singularize model and file names from plural table names [boolean] 

3.对应数据库操作符的定义

 const { Op } = sequelize; [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', 使用数据库语言特定的列标识符, 本例使用 
 $and: {a: 5} // AND (a = 5) $or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6) $gt: 6, // > 6 $gte: 6, // >= 6 $lt: 10, // < 10 $lte: 10, // <= 10 $ne: 20, // != 20 $not: true, // IS NOT TRUE $between: [6, 10], // BETWEEN 6 AND 10 $notBetween: [11, 15], // NOT BETWEEN 11 AND 15 $in: [1, 2], // IN [1, 2] $notIn: [1, 2], // NOT IN [1, 2] $like: '%hat', // LIKE '%hat' $notLike: '%hat' // NOT LIKE '%hat' $iLike: '%hat' // ILIKE '%hat' (case insensitive) (PG only) $notILike: '%hat' // NOT ILIKE '%hat' (PG only) $like: { $any: ['cat', 'hat']} // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike $overlap: [1, 2] // && [1, 2] (PG array overlap operator) $contains: [1, 2] // @> [1, 2] (PG array contains operator) $contained: [1, 2] // <@ [1, 2] (PG array contained by operator) $any: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only) $col: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example 
 //or操作符的两种使用 order_status=0 or order_status=1 params['$or'] = [{ order_status: 0 }, { order_status: 1 }]; params['order_status'] = { $or: [ { $eq: 0 }, { $eq: 1 } ] } 

4. 增删改查(CRUD)

1. 增加

create

向数据库中添加单条记录。

提示: 本文由整理自网络,如有侵权请联系本站删除!
本站声明:
1、本站所有资源均来源于互联网,不保证100%完整、不提供任何技术支持;
2、本站所发布的文章以及附件仅限用于学习和研究目的;不得将用于商业或者非法用途;否则由此产生的法律后果,本站概不负责!

-六神源码网