Sequelize 是 Node 的一個 ORM(Object-Relational Mapping) 框架,用來方便數據庫操作。
配置 sequelize
以 mysql 為例
首先我們要引入npm包,sequelize 依賴 mysql2 作為底層驅動,暴露出自己的 API 讓我們調用,在轉成 mysql 語句進行執行。
"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 如何映射數據庫表
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 會自動為我們添加創建時間和更新時間,我一般選擇關閉,手動添加靈活性高些。
增刪改查
增
(async () => { const now = Date.now() const user = await UserModel.create({ username: '小張', password: 'root', createAt: now, updateAt: now, }) console.log('創建:' + JSON.stringify(user)) })();
查
(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), }) })();
改
(async () => { // 方法一 await UserModel.upert(data) // data 里面如果帶有 id 則更新,不帶則新建 // 方法二 const user = await UserModel.findById(id) user.update(data) })()
刪
(async () => { // 方法一 // 刪除所有名字帶’小‘的用戶 await UserModel.destroy({ where: { username: '小', }, }) // 方法二 const user = await UserModel.findById(id) user.destroy() })()