Sequelize ORM
1.數據的增刪改查與事務
初始化模型
const { Sequelize, Model, DataTypes } = require("sequelize");
const sequelize = new Sequelize({
dialect: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "password",
database: "demo",
timezone: "+08:00",
pool: {
max: 10,
min: 0
},
logging: true,
});
class User extends Model {}
User.init({
id: {
type: DataTypes.INTEGER({ unsigned: true }),
primaryKey: true,
autoIncrement: true,
comment: "用戶ID",
},
username: {
type: DataTypes.STRING(40),
unique: true,
allowNull: false,
comment: "賬號",
},
password: {
type: DataTypes.CHAR(64),
allowNull: false,
comment: "密碼",
},
}, {
sequelize: sequelize,
tableName: "user",
modelName: "user",
paranoid: true, // 邏輯刪除,填充刪除時間
underscored: true, // 內置字段用下划線代替駝峰命名
});
-
增
-
單條插入
(async ()=>{ try{ await sequelize.sync({force: true}); const user = await User.create({ username: "mkl", password: "123456", }); console.log("創建成功", user.toJSON()); } catch(e){ console.log(e); } })();
-
批量插入
(async ()=>{ try{ await sequelize.sync({force: true}); const users = await User.bulkCreate([ {username: "mkl", password: "123456"}, {username: "bob", password: "123456"}, ], { individualHooks: true, // 對每個數據都執行一次生命周期,為false只執行bulkCreate的生命周期 }); console.log("創建成功", users.map(user=>user.toJSON())); } catch(e){ console.log(e); } })();
-
-
更新
-
批量更新
(async ()=>{ try{ // await sequelize.sync({force: true}); const [count, users] = await User.update({username: "bob", password: "123456"}, { where: { username: 'marry', }, individualHooks: true, // 對每個數據都執行一次生命周期,為false只執行bulkCreate的生命周期 }); console.log(`總共更新了${count}`, users.map(user=>user.toJSON())); } catch(e){ console.log(e); } })();
-
單條更新
(async ()=>{ try{ const user = await User.findOne({ where: { username: "bob" } }); if (!user){ throw new Error("用戶不存在."); } user.password = "password"; await user.save(); console.log(user.toJSON()); } catch(e){ console.log(e); } })();
-
-
刪除
- 批量刪除(邏輯)
(async ()=>{ try{ const count = await User.destroy({ where: { username: "bob" } }); console.log(`刪除了${count}條數據.`) } catch(e){ console.log(e); } })();
- 單條刪除(物理)
- 批量刪除(邏輯)
-
查詢
-
單條查詢
根據ID查詢
(async ()=>{ /** * 根據ID查詢 */ const userById = await User.findByPk(1); console.log(userById?userById.toJSON():"未查到數據"); })();
findOne根據where查詢
(async ()=>{ /** * 根據條件查詢,並返回指定字段 */ const user = await User.findOne({ attributes: ["password"], where: { username: "mkl", } }); console.log(user?user.toJSON():"未查到數據"); })();
-
多條查詢
(async ()=>{ /** * 根據條件查詢,並返回指定字段 */ const user = await User.findAll({ attributes: ["password"], where: { username: "mkl", }, order: [ ["id", "DESC"], ["username", "DESC"], ], offset: 0, limit: 10 }); console.log(user); })();
-
查詢或創建單條數據
(async ()=>{ /** * 根據條件查詢,並返回指定字段 */ const [user, created] = await User.findOrCreate({ where: { username: "bob", }, defaults: { username: "bob", password: "password", } }); if (created){ console.log("創建用戶成功", user.toJSON()); } else { console.log("查詢用戶成功", user.toJSON()); } console.log(user); })();
-
同時查詢列表和數據總數
(async ()=>{ const {rows, count} = await User.findAndCountAll({ where: { username: "mkl", } }); console.log(rows.map(row=>row.toJSON()), count); })();
-
統計數據
(async () => { const count = await User.count({ where: { username: "mkl", } }); console.log(count); })();
-
運算符
查看上一篇博客
-
-
事務
-
自動事務
(async () => { const result = await sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE // 設置隔離級別 }, async (transaction) => { const user = await User.create({ username: "marry", password: 123, }, {transaction: transaction}); // 選項中必須傳遞事務對象 const user2 = await User.create({ username: "jerry", password: 456, }, {transaction: transaction}); return [user, user2]; }); console.log(result.map(user=>user.toJSON())); })();
-
手動事務
(async () => { const transaction = await sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE, }); try{ const user = await User.create({ username: "miaokela", password: "password", }, {transaction: transaction}); const user2 = await User.create({ username: "boby", password: "123456", }); await transaction.commit(); } catch(e){ await transaction.rollback(); throw e; } })();
-