sequlize操作mysql小记

增加数据操作

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
  1. 迁移文件
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()

复杂多表操作、多函数共享事务、条件回滚 → 手动事务更稳妥。

简单操作、一两步即可完成 → 自动事务写起来方便。

相关推荐
掉头发的王富贵6 分钟前
ShardingSphere-JDBC入门教程(上篇)
spring boot·后端·mysql
前端程序猿i12 分钟前
用本地代理 + ZIP 打包 + Excel 命名,优雅批量下载跨域 PDF
前端·javascript·vue.js·html
盖世英雄酱5813615 分钟前
必须掌握的【InheritableThreadLocal】
java·后端
LovelyAqaurius16 分钟前
乐观锁及其实现方式详解
后端
绝无仅有19 分钟前
编写 Go 项目的 Dockerfile 文件及生成 Docker 镜像
后端·面试·github
Danny_FD21 分钟前
Vue2 中使用vue-markdown实现编辑器
前端·javascript·vue.js
用户游民21 分钟前
Flutter 项目热更新加载 libapp.so 文件
前端
coding随想21 分钟前
Vue和React对DOM事件流的处理方法解析
前端
用户479492835691523 分钟前
字节面试官:forEach 为什么不能被中断?
前端·javascript
ccnocare23 分钟前
window.electronAPI.send、on 和 once
前端·electron