Sequelize 是 Node 的一个 ORM(Object-Relational Mapping) 框架,用来方便数据库操作。

配置 sequelize

 

以 mysql 为例

首先我们要引入npm包,sequelize 依赖 mysql2 作为底层驱动,暴露出自己的 API 让我们调用,在转成 mysql 语句进行执行。

"mysql2": "^1.5.1",
"sequelize": "^4.28.6"
const Sequelize = require('sequelize')

// 连接数据库
const sequelize = new Sequelize('database', 'username', 'password', {
  host: sqlconf.host,
  dialect: 'mysql', // 这里可以改成任意一种关系型数据库

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
})

// 测试连接是否成功
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.')
  })
  .catch(err => {
    console.log('Unable to connect to the database', err)
  })

// 根据 model自动创建表
sequelize
  .sync()
  .then(() => {
    console.log('init db ok')
  })
  .catch(err => {
    console.log('init db error', err)
  })

  

我们可以调用sync()根据 model自动在数据库中创建表,也可以不调用,自己手动创。如果使用了 Sequelize 的 Associations,这必须通过 sync() 生成表结构。

创建 model

创建模型,告诉 Sequelize 如何映射数据库表

const UserModel = sequelize.define('user', {
  id: {
    type: Sequelize.INTEGER(11),
    primaryKey: true,            // 主键
    autoIncrement: true,         // 自动递增
  },
  username: Sequelize.STRING(100),
  password: Sequelize.STRING(100),
  createdAt: Sequelize.BIGINT,
  updatedAt: Sequelize.BIGINT,
}, {
  timestamps: false
})

  

define() 方法的第一个参数为表名,对应的是 users 表。如果不设置 timestamps,Sequlize 会自动为我们添加创建时间和更新时间,我一般选择关闭,手动添加灵活性高些。

增删改查

(async () => {
  const now = Date.now()
  const user = await UserModel.create({
    username: '小张',
    password: 'root',
    createAt: now,
    updateAt: now,
  })
  console.log('创建:' + JSON.stringify(user))
})();

  

(async () => {
  // 查找所有
  const allUser = await UserModel.findAll()

  // 按id查找
  const oneUser = await UserModel.findById(id)

  // 按条件查询
  const someUser = await UserModel.findAll({
    where: {
      // 模糊查询
      name: {
        $like: '%小%',
      },

      // 精确查询
      password: 'root',
    }
  })

  // 分页查询
  const size = 10 // 每页10条数据
  const page = 1 // 页数
  const pageUser = await UserModel.findAndCountAll({
    where: {
      name: {
        $like: '%小%',
      },
    },
    limit: size,
    offset: size * (page - 1),
  })
})();

  

(async () => {
// 方法一
await UserModel.upert(data)  // data 里面如果带有 id 则更新,不带则新建

// 方法二
const user = await UserModel.findById(id)
user.update(data)
})()

  

(async () => {
// 方法一
// 删除所有名字带’小‘的用户
await UserModel.destroy({
  where: {
    username: '小',
  },
})

// 方法二
const user = await UserModel.findById(id)
user.destroy()
})()

操作符

别名对照(左边为别名)

const operatorsAliases = {
$eq: Op.eq,
$ne: Op.ne,
$gte: Op.gte,
$gt: Op.gt,
$lte: Op.lte,
$lt: Op.lt,
$not: Op.not,
$in: Op.in,
$notIn: Op.notIn,
$is: Op.is,
$like: Op.like,
$notLike: Op.notLike,
$iLike: Op.iLike,
$notILike: Op.notILike,
$regexp: Op.regexp,
$notRegexp: Op.notRegexp,
$iRegexp: Op.iRegexp,
$notIRegexp: Op.notIRegexp,
$between: Op.between,
$notBetween: Op.notBetween,
$overlap: Op.overlap,
$contains: Op.contains,
$contained: Op.contained,
$adjacent: Op.adjacent,
$strictLeft: Op.strictLeft,
$strictRight: Op.strictRight,
$noExtendRight: Op.noExtendRight,
$noExtendLeft: Op.noExtendLeft,
$and: Op.and,
$or: Op.or,
$any: Op.any,
$all: Op.all,
$values: Op.values,
$col: Op.col
};

原始解释

const Op = Sequelize.Op

[Op.and]: {a: 5} // 且 (a = 5)
[Op.or]: [{a: 5}, {a: 6}] // (a = 5 或 a = 6)
[Op.gt]: 6, // id > 6
[Op.gte]: 6, // id >= 6
[Op.lt]: 10, // id < 10
[Op.lte]: 10, // id <= 10
[Op.ne]: 20, // id != 20
[Op.eq]: 3, // = 3
[Op.not]: true, // 不是 TRUE
[Op.between]: [6, 10], // 在 6 和 10 之间
[Op.notBetween]: [11, 15], // 不在 11 和 15 之间
[Op.in]: [1, 2], // 在 [1, 2] 之中
[Op.notIn]: [1, 2], // 不在 [1, 2] 之中
[Op.like]: '%hat', // 包含 '%hat'
[Op.notLike]: '%hat' // 不包含 '%hat'
[Op.iLike]: '%hat' // 包含 '%hat' (不区分大小写) (仅限 PG)
[Op.notILike]: '%hat' // 不包含 '%hat' (仅限 PG)
[Op.regexp]: '^[h|a|t]' // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.iRegexp]: '^[h|a|t]' // ~* '^[h|a|t]' (仅限 PG)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)
[Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 同样适用于 iLike 和 notLike
[Op.overlap]: [1, 2] // && [1, 2] (PG数组重叠运算符)
[Op.contains]: [1, 2] // @> [1, 2] (PG数组包含运算符)
[Op.contained]: [1, 2] // <@ [1, 2] (PG数组包含于运算符)
[Op.any]: [2,3] // 任何数组[2, 3]::INTEGER (仅限PG)

[Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG

  

 

sequelize 数据类型 model
 
posted on 2020-08-07 14:56  ygunoil  阅读(1594)  评论(0编辑  收藏  举报