sequelize基础知识学习整理 sequelize文档
安装 1 2 3 4 5 6 npm install --save sequelize npm install --save pg pg-hstore npm install --save mysql2 npm install --save sqlite3 npm install --save tedious // MSSQL
连接 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 const Sequelize = require ('sequelize' );const sequelize = new Sequelize('database' , 'username' , 'password' , { host: 'localhost' , port: port, dialect: 'mysql' |'sqlite' |'postgres' |'mssql' , operatorsAliases: false , pool: { max: 5 , min: 0 , acquire: 30000 , idle: 10000 }, storage: 'path/to/database.sqlite' }); sequelize .authenticate() .then(() => { console .log('Connection has been established successfully.' ); }) .catch(err => { console .error('Unable to connect to the database:' , err); });
model 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 const User = sequelize.define('user' , { firstName: { type: Sequelize.STRING }, lastName: { type: Sequelize.STRING } }, { freezeTableName: true }); User.sync();
mdoel 类型 以下是 Sequelize 支持的一些数据类型.有关完整和更新的列表, 参阅DataTypes
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 Sequelize.STRING Sequelize.STRING(1234 ) Sequelize.STRING.BINARY Sequelize.TEXT Sequelize.TEXT('tiny' ) Sequelize.INTEGER Sequelize.BIGINT Sequelize.BIGINT(11 ) Sequelize.FLOAT Sequelize.FLOAT(11 ) Sequelize.FLOAT(11 , 12 ) Sequelize.REAL Sequelize.REAL(11 ) Sequelize.REAL(11 , 12 ) Sequelize.DOUBLE Sequelize.DOUBLE(11 ) Sequelize.DOUBLE(11 , 12 ) Sequelize.DECIMAL Sequelize.DECIMAL(10 , 2 ) Sequelize.DATE Sequelize.DATE(6 ) Sequelize.DATEONLY Sequelize.BOOLEAN Sequelize.ENUM('value 1' , 'value 2' ) Sequelize.ARRAY(Sequelize.TEXT) Sequelize.ARRAY(Sequelize.ENUM) Sequelize.JSON Sequelize.JSONB Sequelize.BLOB Sequelize.BLOB('tiny' ) Sequelize.UUID Sequelize.CIDR Sequelize.INET Sequelize.MACADDR Sequelize.RANGE(Sequelize.INTEGER) Sequelize.RANGE(Sequelize.BIGINT) Sequelize.RANGE(Sequelize.DATE) Sequelize.RANGE(Sequelize.DATEONLY) Sequelize.RANGE(Sequelize.DECIMAL) Sequelize.ARRAY(Sequelize.RANGE(Sequelize.DATE)) Sequelize.GEOMETRY Sequelize.GEOMETRY('POINT' ) Sequelize.GEOMETRY('POINT' , 4326 )
mdoel defaultValue find 使用 find 搜索数据库中的一个特定元素 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Project.findById(123 ).then(project => { }) Project.findOne({ where: { title: 'aProject' } }).then(project => { }) Project.findOne({ where: {title : 'aProject' }, attributes: ['id' , ['name' , 'title' ]] }).then(project => { })
findOrCreate 搜索特定元素或创建它(如果不可用) 我们有一个空的数据库,一个 User 模型有一个 username 和 job
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 User .findOrCreate({ where: {username : 'sdepold' }, defaults: {job : 'Technical Lead JavaScript' } }) .spread((user, created ) => { console .log(user.get({ plain: true })) console .log(created) })
创建了一个新的实例.所以当我们已经有一个实例了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 User.create({ username : 'fnord' , job : 'omnomnom' }) .then(() => User.findOrCreate({ where: {username : 'fnord' }, defaults: {job : 'something else' } })) .spread((user, created ) => { console .log(user.get({ plain: true })) console .log(created) })
findAndCountAll - 在数据库中搜索多个元素,返回数据和总计数 处理程序成功将始终接收具有两个属性的对象:
count - 一个整数,总数记录匹配where语句和关联的其它过滤器
rows - 一个数组对象,记录在limit和offset范围内匹配where语句和关联的其它过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 Project .findAndCountAll({ where: { title: { [Op.like]: 'foo%' } }, offset: 10 , limit: 2 }) .then(result => { console .log(result.count) console .log(result.rows); })
它支持 include。 只有标记为 required 的 include 将被添加到计数部分:
假设您想查找附有个人资料的所有用户:
1 2 3 4 5 6 User.findAndCountAll({ include: [ { model : Profile, required : true } ], limit: 3 });
因为 Profile 的 include 有 required 设置,这将导致内部连接,并且只有具有 profile 的用户将被计数。 如果我们从 include 中删除required,那么有和没有 profile 的用户都将被计数。 在include中添加一个 where 语句会自动使它成为 required:
1 2 3 4 5 6 User.findAndCountAll({ include: [ { model : Profile, where : { active : true }} ], limit: 3 });
上面的查询只会对具有 active profile 的用户进行计数,因为在将 where 语句添加到 include 时,required 被隐式设置为 true
传递给 findAndCountAll 的 options 对象与 findAll 相同(如下所述)
findAll - 搜索数据库中的多个元素 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 37 38 39 40 41 42 43 44 45 46 47 48 49 Project.findAll().then(projects => { }) Project.all().then(projects => { }) Project.findAll({ where : { name : 'A Project' } }).then(projects => { }) Project.findAll({ where : { id : [1 ,2 ,3 ] } }).then(projects => { }) Project.findAll({ where: { id: { [Op.and]: {a : 5 }, [Op.or]: [{a : 5 }, {a : 6 }], [Op.gt]: 6 , [Op.gte]: 6 , [Op.lt]: 10 , [Op.lte]: 10 , [Op.ne]: 20 , [Op.between]: [6 , 10 ], [Op.notBetween]: [11 , 15 ], [Op.in]: [1 , 2 ], [Op.notIn]: [1 , 2 ], [Op.like]: '%hat' , [Op.notLike]: '%hat' , [Op.iLike]: '%hat' , [Op.notILike]: '%hat' , [Op.overlap]: [1 , 2 ], [Op.contains]: [1 , 2 ], [Op.contained]: [1 , 2 ], [Op.any]: [2 ,3 ], }, status: { [Op.not]: false , } } })
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 var users = await User.findAll({ 'attributes' : ['emp_id' , 'nick' ] }); SELECT `emp_id` , `nick` FROM `users` ; var users = await User.findAll({ 'attributes' : [ 'emp_id' , ['nick' , 'user_nick' ] ] }) SELECT `emp_id` , `nick` AS `user_nick` FROM `users` ; var users = await User.findAll({ 'where' : { 'id' : [1 , 2 , 3 ], 'nick' : 'a' , 'department' : null } }) SELECT `id` , `emp_id` , `nick` , `department` , `created_at` , `updated_at` FROM `user` WHERE `user` .`id` IN (1 , 2 , 3 ) AND `user` .`nick` ='a' AND `user` .`department` IS NULL;
操作符 where
1 2 3 4 5 6 7 8 9 10 11 12 13 14 '$eq' : 1 , '$ne' : 2 , '$gt' : 6 , '$gte' : 6 , '$lt' : 10 , '$lte' : 10 , '$between' : [6 , 10 ], '$notBetween' : [11 , 15 ], '$in' : [1 , 2 ], '$notIn' : [3 , 4 ] '$like' : '%a%' , '$notLike' : '%a' '$eq' : null , '$ne' : null
$and
$or
$not
order 排序
分页 User.findAll({ ‘limit’: countPerPage, // 每页多少条 ‘offset’: countPerPage * (currentPage - 1)// 跳过多少条 })
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var users = await User.findAll({ 'where' : { '$or' : [ {'id' : [1 , 2 ]}, {'nick' : null } ] } }) SELECT `id` , `emp_id` , `nick` , `department` , `created_at` , `updated_at` FROM `user` WHERE ( `user` .`id` IN (1 , 2 ) OR `user` .`nick` IS NULL )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var users = await User.findAll({ 'where' : { '$and' : [ {'id' : [1 , 2 ]}, {'nick' : null } ] } }) SELECT `id` , `emp_id` , `nick` , `department` , `created_at` , `updated_at` FROM `user` WHERE ( `user` .`id` IN (1 , 2 ) AND `user` .`nick` IS NULL )
1 2 3 4 5 6 7 8 9 var users = await User.findAll({ 'where' : { '$not' : [ {'id' : [1 , 2 ]}, {'nick' : null } ] } })
改 update 使用 1 2 3 4 5 6 7 8 9 10 11 user.nick = '小白' ; user = yield user.save(); console .log(user.get({'plain' : true })); user.update({ 'nick' : '小白白' }).then(user => { console .log(user.get({'plain' : true })) })
ffff 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 User.findAll().then((users ) => { console .log(users) }) findAll findOne findById findOrCreate findAndCountAll findAll({ where: { title: 'afacode' }, attributes: ['id' , ['name' , title]] }) findOrCreate({ where: { username: 'afacode' }, defaults: { job: 'FE' } }).spread(user, created) => { }
new Sequelize
sequelize.models 返回通过sequelize.define定义的所有模型对象
sequelize.define
sequelize.Utils
sequelize.Promise
sequelize.QueryTypes 查询类型枚举
sequelize.Validator
sequelize.Transaction 事务对象
project.max(‘age’)
project.min(‘age’)
project.sum(‘age’)
欢迎访问我的博客 地址 https://blog.afacode.top
如有问题可联系 Email:afacode@outlook.com 或 微信:afacode