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()

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

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

相关推荐
非凡ghost8 小时前
PixPin截图工具(支持截长图截动图) 中文绿色版
前端·javascript·后端
武子康8 小时前
大数据-133 ClickHouse 概念与基础|为什么快?列式 + 向量化 + MergeTree 对比
大数据·后端·nosql
૮・ﻌ・8 小时前
Vue2(一):创建实例、插值表达式、Vue响应式特性、Vue指令、指令修饰符、计算属性
前端·javascript·vue.js
脚踏实地的大梦想家8 小时前
【Go】P11 掌握 Go 语言函数(二):进阶玩转高阶函数、闭包与 Defer/Panic/Recover
开发语言·后端·golang
半生过往9 小时前
2025 前端动效实战指南:Vue Bits & React Bits 深度拆解(功能 / 复用 / 高频问题处理)
前端·vue.js·react.js
程序员包打听9 小时前
Vitest 4.0 重磅发布:Browser Mode 正式稳定,前端测试进入新纪元
前端
BumBle9 小时前
UniApp 多页面编译优化:编译时间从10分钟到1分钟
前端
星链引擎9 小时前
大语言模型的技术突破与稳定 API 生态的构建
前端
还是大剑师兰特9 小时前
TypeScript 面试题及详细答案 100题 (71-80)-- 模块与命名空间
前端·javascript·typescript
BumBle9 小时前
使用 SortableJS 实现vue3 + Element Plus 表格拖拽排序
前端·vue.js·element