Sequelizejs框架学习(待更新)

安装

npm install sequelize -S

npm install sequelize-cli -S

npx sequelize-cli init

model

如果你不想使用sql语句,那么你需要建立模型

model可以方便数据校验,数据关联等

可以用一下快捷命令创建model

sequelize-auto  -h ip -d 库名 -u 用户名 -x 密码 -p 端口号  -o 生成模型的路径 -t 表名

注意sequelize-auto要全局安装(npm i sequelize-auto -g)

model组件格式:

const { DataTypes } = require("sequelize");
const sequelize = require("../mysql");
const myModel = sequelize.define('roadsection', {
    id: {
      autoIncrement: true,
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true
    },
    ...
});
module.exports = myModel

sequlize函数

检测链接

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

基础语句:

update不需要给全部参数,没有的自动保持不变不更新

// 插入语句
model.create({...})     
   
// 查询语句
// 如果全查就不要attributes
model.findAll({attributes: ['a', 'b']})
//也可以使用聚合函数
attributes: [
    'a',
    [sequelize.fn('COUNT', sequelize.col('c')), 'n_c'],
    'b'
  ]            
// 也可以使用includes(这个表示全选还要加上includes的)和excludes(全选去掉excludes的)

// 更新语句
model.update({},{where:{xxx:'xxx'}})

// 删除语句
model.destroy({where:{xxx:'xxx'}})
// 如果要全删
model.destroy({
  truncate: true
});

// 批量创建
model.bulkCreate([
  {},
  {}
]);

findOrCreate

const [record, created] = await model.findOrCreate({
			where: { 
                // 查询条件
             },
			defaults: {
				// 如果没有查到,则要插入的数据
			}
		});
// created是true说明没查到,新增了一条,record表示这条的数据
// record可以直接.update({更新后的数据})

这个findOrCreate有个非常不合理的地方 ,如果你有字段在model里定义的是非空的,并且没有默认值,那么如果你的where里没有这个字段就会报错;那这时候你是不是想说那就给个默认值呗,根本不行,因为你给了默认值它就只插入默认值了,你后面的default它根本不走。

总结:不用,你要是只有一个字段或者没有字段是非空(不是那种自增的id)的并且你查询只用这个就行,那你可以用这个,否则别用!

异步的.then()

findAll有.then,里面的回调函数的参数是查询到的结果
注意:不是所有的语句都有result返回,比如destroy,如果你想得到删除的数据,只能先查再删

OP

AND

where:{
    [Op.and]: [
      { a: 1 },
      { b: 2 }
    ]
}

这个相当于where a = 1 AND b = 2

OR

where: {
    a: {
      [Op.or]: [1, 2]
    }
  }

or除了和and一样的用法,在同一字段的情况下,还可以放在一起

其他Op

除了or和and,还有很多别的常见的Op如下所示参考中文官网

someAttribute: {
      // 基本
      [Op.eq]: 3,                              // = 3
      [Op.ne]: 20,                             // != 20
      [Op.is]: null,                           // IS NULL
      [Op.not]: true,                          // IS NOT TRUE
      [Op.or]: [5, 6],                         // (someAttribute = 5) OR (someAttribute = 6)

      // 使用方言特定的列标识符 (以下示例中使用 PG):
      [Op.col]: 'user.organization_id',        // = "user"."organization_id"

      // 数字比较
      [Op.gt]: 6,                              // > 6
      [Op.gte]: 6,                             // >= 6
      [Op.lt]: 10,                             // < 10
      [Op.lte]: 10,                            // <= 10
      [Op.between]: [6, 10],                   // BETWEEN 6 AND 10
      [Op.notBetween]: [11, 15],               // NOT BETWEEN 11 AND 15

      // 其它操作符

      [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1)

      [Op.in]: [1, 2],                         // IN [1, 2]
      [Op.notIn]: [1, 2],                      // NOT IN [1, 2]

      [Op.like]: '%hat',                       // LIKE '%hat'
      [Op.notLike]: '%hat',                    // NOT LIKE '%hat'
      [Op.startsWith]: 'hat',                  // LIKE 'hat%'
      [Op.endsWith]: 'hat',                    // LIKE '%hat'
      [Op.substring]: 'hat',                   // LIKE '%hat%'
      [Op.iLike]: '%hat',                      // ILIKE '%hat' (不区分大小写) (仅 PG)
      [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (仅 PG)
      [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (仅 MySQL/PG)
      [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (仅 MySQL/PG)
      [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (仅 PG)
      [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (仅 PG)

      [Op.any]: [2, 3],                        // ANY (ARRAY[2, 3]::INTEGER[]) (PG only)
      [Op.match]: Sequelize.fn('to_tsquery', 'fat & rat') // 匹配文本搜索字符串 'fat' 和 'rat' (仅 PG)

      // 在 Postgres 中, Op.like/Op.iLike/Op.notLike 可以结合 Op.any 使用:
      [Op.like]: { [Op.any]: ['cat', 'hat'] }  // LIKE ANY (ARRAY['cat', 'hat'])

    }

Op.in省略

Post.findAll({
  where: {
    id: [1,2,3] // 等同使用 `id: { [Op.in]: [1,2,3] }`
  }
});

Op套娃

[Op.or]: {
        [Op.lt]: 1000,
        [Op.eq]: null
      }

获取器

在model中设置获取器,在查询等获得值的时候执行get函数,一般用来进行字段格式规范

const User = sequelize.define('user', {
  // 假设我们想要以大写形式查看每个用户名,
  // 即使它们在数据库本身中不一定是大写的
  username: {
    type: DataTypes.STRING,
    get() {
      const rawValue = this.getDataValue('username');
      return rawValue ? rawValue.toUpperCase() : null;
    }
  }
});

设置器

除了获取器,我们也可以设置设置器来规范输入(insert插入等)

set(value) {
      // 在数据库中以明文形式存储密码是很糟糕的.
      // 使用适当的哈希函数来加密哈希值更好.
      this.setDataValue('password', hash(value));
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值