增加数据操作
js
const { Account } = require('@/modules')
Account.create({username: '小张', age: 18})
查询操作
js
const { Account } = require('@/modules')
const {Op} = require('sequelize')
Account.findAll(where:{username: '小张'}) // 表示查询出名字小张的 数组数据
Account.findOne(where:{username: '小张'}) // 表示查询出名字小张的 单个数据
//raw 就是控制台返回的是跑通对象 和 mongose 的leave() 一样的效果
Account.findAll(where:{username: '小张'}, raw: true)
// 表示和的 查询两个都要满足
Account.findAll(where:{username: '小张', age: 18}, raw: true)
// 或者查询 表示满足其中一个条件就可以
Account.findAll(where:[Op.or]:{username: '小张', age: 18}, raw: true)
修改操作
js
const { Account } = require('@/modules')
const {Op} = require('sequelize')
// 表示把小张修改成 小肖
Account.findAll({username: '小肖'}, where:{username: '小张'})
删除操作
js
const { Account } = require('@/modules')
const {Op} = require('sequelize')
// 表示删除操作
Account.destory(where:{username: '小张'})
一对一关系查询操作
关系:一个桌子对应一个学生(One-To-One)。
桌子有 studentId 外键,指向学生。
js
npx sequelize-cli model:generate --name Student --attributes name:STRING,age:INTEGER
npx sequelize-cli model:generate --name Table --attributes location:STRING,studentId:BIGINT
- 迁移文件
js
migrations/xxxx-create-students.js
'use strict'
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Students', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
age: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Students')
}
}
js
migrations/xxxx-create-tables.js
'use strict'
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Tables', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
location: {
type: Sequelize.STRING
},
studentId: { // 外键
type: Sequelize.BIGINT,
references: {
model: 'Students',
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL'
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Tables')
}
}
2、模型文件 models/student.js
js
'use strict'
module.exports = (sequelize, DataTypes) => {
const Student = sequelize.define('Student', {
name: DataTypes.STRING,
age: DataTypes.INTEGER
})
学生表连接桌子表
Student.associate = function(models) {
Student.hasOne(models.Table, {
foreignKey: 'studentId',
as: 'table'
})
}
return Student
}
models/table.js
js
'use strict'
module.exports = (sequelize, DataTypes) => {
const Table = sequelize.define('Table', {
location: DataTypes.STRING
})
桌子是属于一个学生的
Table.associate = function(models) {
Table.belongsTo(models.Student, {
foreignKey: 'studentId',
as: 'student'
})
}
return Table
}
查询
js
// 查询学生及其桌子
const stuWithTable = await Student.findOne({
where: { name: '小明' },
include: [{ model: Table, as: 'table' }]
})
console.log(stuWithTable.toJSON())
// 查询桌子及其学生
const tableWithStudent = await Table.findOne({
where: { location: '教室A1' },
include: [{ model: Student, as: 'student' }]
})
console.log(tableWithStudent.toJSON())
一对多的关系查询
js
Class.hasMany(models.Student,{ foreignKey: 'class_id', as: 'sthdentList' })
Class.hasMany(...) 👉 意思是 "一个班级有很多学生",也就是"一对多"的关系。
foreignKey: 'class_id' 👉 数据库里,学生表里有一个 class_id 字段,用来指向班级。
这个字段就是外键,把学生和班级关联起来。
as: 'studentList' 👉 给这个关联起个名字,方便你在查询时使用:
js
Student.belongsTo(models.Class, { foreignKey: 'class_id', as: 'classDetail' }
Student.belongsTo(...) 👉 意思是 "每个学生属于一个班级",也就是"多对一"的关系。
foreignKey: 'class_id' 👉 表示学生表里 class_id 字段指向班级表。
as: 'classDetail' 👉 给这个关联起个名字,方便你查学生时访问班级:
查询
js
Class.findOne({
where: { id: classId },
include: [
{
model: Student,
as: 'studentList' // 对应 hasMany 的 as
}
]
})
Student.findOne({
where: { id: studentId },
include: [
{
model: Class,
as: 'classDetail' // 对应 belongsTo 的 as
}
]
})
事务
事务就是把多个数据库操作 打包成一个整体,要么全部成功,要么全部回滚。
适用于涉及多个表或多条数据的操作,保证数据一致性。 AICD特性
非托管事务(手动)推荐
js
const { sequelize, Student, Table } = require('./models')
async function createStudentAndTable() {
// 开启事务
const t = await sequelize.transaction()
try {
// 1️⃣ 创建学生
const student = await Student.create(
{ name: '小红', age: 20 },
{ transaction: t } // 注意:每条操作都要绑定 transaction
)
// 2️⃣ 创建桌子并关联学生
const table = await Table.create(
{ location: '教室B1', studentId: student.id },
{ transaction: t }
)
// ✅ 所有操作成功 → 提交事务
await t.commit()
console.log('创建成功:', student.toJSON(), table.toJSON())
} catch (err) {
// ❌ 出错 → 回滚事务
await t.rollback()
console.error('操作失败,事务已回滚', err)
}
}
createStudentAndTable()
托管事务
js
const { sequelize, Student, Table } = require('./models')
async function createWithAutoTransaction() {
try {
await sequelize.transaction(async (t) => {
const student = await Student.create(
{ name: '小明', age: 18 },
{ transaction: t } // 每条操作都需要传 transaction
)
const table = await Table.create(
{ location: '教室C1', studentId: student.id },
{ transaction: t }
)
console.log('创建成功:', student.toJSON(), table.toJSON())
// 如果这里抛异常,Sequelize 会自动回滚事务
})
} catch (err) {
console.error('事务失败,已回滚', err)
}
}
createWithAutoTransaction()
复杂多表操作、多函数共享事务、条件回滚 → 手动事务更稳妥。
简单操作、一两步即可完成 → 自动事务写起来方便。