美文网首页
Sequelize 操作 MySQL数据库方法

Sequelize 操作 MySQL数据库方法

作者: Y_B_T | 来源:发表于2019-05-12 23:44 被阅读0次

前言:以下是本人学习Sequelize,与工作中使用过的一些方法,基本上参考与Sequelize 快速入门

新增

build 方法( 需要使用save方法才能保存到数据库中)

let user = UserModel.build({
   name: "JackTeng",
   age: "24"
});
user = await user.save();

create 方法(直接保存到数据中)

const user = await UserModel.create({
   name: "JackTeng",
   age: "24"
});

更新

update 方法(注意:更新失败返回值到第0个值是0,更新成功则是1)

const updatedUser = await user.update(
{
  name: "JackTeng",
  age: "25"
},
{
   where: {id: 1}
}
);

删除

destroy 方法

const destroyUser = await user.destroy({
     where:{ id: 1 }
});

查询

findAll 方法(查询全部)

const users = await User.findAll();

筛选字段查询(注意:只会返回attribute数组中到字段)

const users = await UserModel.findAll({
    attributes: ['id', 'name', 'age']
});

字段重命名(注意重新命名是:原数据库返回的字段名,更改为当前名)

const users = await UserModel.findAll({
   attributes: ['id', 'age', ['name', 'name_a']]
});

条件查询

const users = await UserModel.findAll({
    attributes: ['id', 'name'],
    where: {
        name: 'JackTeng'
    }
});

AND 条件

const Op = Sequelize.Op;
const users = await UserModel.findAll({
      attributes: ['id', 'name'],
      where: {
          [Op.and]: [
              { id: [1, 2] },
              { name: 'JackTeng' }
          ]
      }
});

OR 条件

const Op = Sequelize.Op;
const users = await UserModel.findAll({
      attributes: ['id', 'name'],
      where: {
            [Op.or]: [
                { id: [1, 2] },
                { name: 'JackTeng' }
             ]
       }
});

NOT 条件

const Op = Sequelize.Op;
const users = await UserModel.findAll({
      attributes: ['id', 'firstName'],
      where: {
           [Op.not]: [
               { id: [1, 2] }
            ]
      }
});

查询单条记录

findById 方法

const user = await UserModel.findById(1);

findByPk 方法

// 温馨提示 Sequelize v5+的版本 findById 已经被移除了,改用 findByPk 替换
const user = await UserModel.findByPk(1);

findOne 方法

const user = await UserModel.findOne({
      where: { name: 'JackTeng' }
});

查询并获取数量

findAndCountAll 方法(会返回总条数)

const result = await UserModel.findAndCountAll({
      limit: 10, // 每页多少条
      offset: 0 // 跳过当前多少条
});

排序与分页

排序

const users = await UserModel.findAll({
      attributes: ['id', 'firstName'],
      order: [
          ['id', 'DESC']
       ]
});

分页

let countPerPage = 2, currentPage = 1;

const users = await UserModel.findAll({
      attributes: ['id', 'name'],
      limit: countPerPage, // 每页多少条
      offset: countPerPage * (currentPage - 1) // 跳过多少条
});

批量操作

插入

const users = await UserModel.bulkCreate([
      { name: "JackTeng", age: "24"},
      { name: "King", age: "26"},
      { name: "ben", age: "30"}
]);

更新

const Op = Sequelize.Op;
const affectedRows = await UserModel.update(
        { firstName: "King" },
        { 
           where: {
              [Op.not]: { firstName: null }
            } 
         }
);

删除(注意:老铁慎用呀)

const affectedRows = await UserModel.destroy({
      where: { name: 'JackTeng' }
});

关联查询(首先需要在model里定义关系)

Model

// ./app/model
'use strict';
module.exports = function(app) {
    const DataTypes = app.Sequelize;
    const UserInfo = app.model.define('user_info', {...});

    // UsersInfo(源) 关联 UserMessage(外键)
    UserInfo.associate = function() {
        UserInfo.hasMany(app.model.UserMessage, {
            foreignKey: 'user_id',  // 外键(要查询的另外一个表), 要查询的字段
            sourceKey: 'user_id',  // 源(当前查询的表),要查询的字段
        });
    };

    return UserInfo
};

Service

// ./app/service
'use strict';

const Service = require('egg').Service;
module.exports = app => {
    const {
        UserInfo,
        UserMessage
    } = app.model;

   class TestService extends Service {
         async getUserAndMessage(){
              // 获取用户和信息
            let result =  await UserInfo.findAll({
                raw: true, // 转为data,而不是实例对象
                include: [{
                    model: UserMessage,
                }]
            });
         }
    }

    return TestService
}

操作符:

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', 使用数据库语言特定的列标识符,

总结:

每天累计一点新知识,下一个大神就是你~

相关文章

网友评论

      本文标题:Sequelize 操作 MySQL数据库方法

      本文链接:https://www.haomeiwen.com/subject/lpnhaqtx.html