sequelize基本用法

"mysql2": "^2.3.3",

   "sequelize": "^6.21.3"

 配置项

const config = {
  host: "127.0.0.1",
  username: "root",
  password: "123456",
  database: "mytest",
  dialect: "mysql",
  timezone: "Asia/Shanghai",
};

module.exports = config;

连接数据库

const { Sequelize } = require('sequelize')
const config = require('../config/index')

const sequelize = new Sequelize(config)

module.exports = sequelize

测试连接,完成后

try {
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

创建模型,如果出现 xxx120,那就是配置项错了,直接复制代码就可以了

const { DataTypes } = require('sequelize')

const sequelize = require('../db/mysqldb2')

const BookModel = sequelize.define(
  'bookt',
  {
    username: {
      type: DataTypes.STRING,
      allowNull: false
    },
    price: {
      type: DataTypes.INTEGER
    }
  },
  {
    paranoid: true
  }
)

sequelize.sync({
  force: false,
  alter: true
})

// 导出模型  创建表的时候默认会创建 id 自动增长,唯一,主演,不为空
module.exports = BookModel

这里开启软删除,会自动创建 createAt  updateAt deleteAt 字段,不用在意

 

// type:      字段类型,String|DataTypes

// allowNull:   是否允许为空,默认为true

// defaultValue:  默认值,默认为null

// unique:      值唯一,默认为false

// primaryKey:    是否为主键,默认为false

// field:       数据库中字段的实际名称

// autoIncrement: 是否自增,默认false

// get:      字段的getter,函数

// set:            字段的setter,函数

// validate:       对象,对当前字段值发生改变的时候进行验证

timestamps:是否给每条记录添加 createdAt 和 updatedAt 字段,并在添加新数据和更新数据的时候自动设置这两个字段的值,默认为true paranoid:设置 deletedAt 字段,当删除一条记录的时候,并不是真的销毁记录,而是通过该字段来标识,即保留数据,进行假删除,默认为false freezeTableName:禁用修改表名; 默认情况下,sequelize将自动将所有传递的模型名称(define的第一个参数)转换为复数。 默认为false tableName:手动设置表的实际名称

 测试增删改差

const { Op } = require('sequelize')
const bookModel = require('../modules/BookModel')

const bookAdd = async (username, price) => {
  const res = await bookModel.create({
    username,
    price
  })
  console.log('======', JSON.stringify(res, null, 2))
}

// bookAdd('aaa', 3)
// bookAdd('wbbbww', 4)
// bookAdd('ccc', 5)

const bookUpdate = async (id) => {
  const res = await bookModel.update(
    { price: 33 },
    {
      where: {
        id
      }
    }
  )
  console.log('======', res)
}

const bookDelete = async (id) => {
  const res = await bookModel.destroy({
    where: {
      id
    }
    // force: true  硬删除
  })
  console.log('======', res)
}
// bookDelete(4)

const bookQuery = async (id) => {
  const res = await bookModel.findByPk(id)
  console.log('======', JSON.stringify(res, null, 2))
}
// bookQuery(4)

const bookQueryAt = async (id) => {
  const res = await bookModel.findByPk(id, { paranoid: false })
  console.log('======', JSON.stringify(res, null, 2))
}
// bookQueryAt(4)
const bookQueryAll = async () => {
  const res = await bookModel.findAll({
    attributes: ['price', 'username'],
    where: {
      username: { [Op.like]: '%a%' }
    }
  })
  console.log('符合条件的', JSON.stringify(res, null, 2))
}

const bookQueryCountAll = async (offset, limit) => {
  const { count, rows } = await bookModel.findAndCountAll({
    offset, // 页数
    limit // 多少条
  })
  console.log('====count=====', count) // 3
  console.log('=====rows======', JSON.stringify(rows, null, 2)) // []
}
bookQueryCountAll(0, 3)

完成后可以写接口了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaodunmeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值