Node項目使用Sequelize(二)(包括條件查詢、排序、分頁,批量增刪改等)


續上一篇 Node項目使用Sequelize操作數據庫(一)(包括模型,增,刪、改等)

本篇包括(條件查詢、AND 、OR 、NOT 、排序和分頁、批量操作等)

1. 查詢

  •  查詢全部

模型.findAll(findOptions: Object)
        在數據庫中搜索多個記錄,返回數據和總計數
        findOptions.where:搜索條件
        findOptions.limit:記錄條數限制
        findOptions.offset:記錄偏移
        findOptions.order:記錄排序方式

Sequelizewhere 配置項完美支持了 SQLwhere 子句的功能

const users = await UsersModel.findAll({
  attributes: ['id', 'username', 'password'],
  where: {
     id: [4,5],
     username: 'John'
  }
});
// 找到之后更改一下它的password 因為findAll 返回的是一個數組
users[0].password = '111111111111111111'
users[0].save();
// 最后得到的users只有一條符合條件

鍵值對被轉換成了 key = value 的形式,若一個對象包含多個鍵值對會被轉換成了 AND 條件,即:k1: v1, k2: v2 轉換為 k1 = v1 AND k2 = v2

2. AND 條件

const Op = Sequelize.Op;
const users = await UsersModel.findAll({
  attributes: ['id', 'username', 'password'],
  where: {
    [Op.and]: [
      {id: [4,5]},
      {username: 'John'}
    ]   
  }
});
users[0].password = '105555555'
users[0].save();
console.log(users);

3. OR 條件

const Op = Sequelize.Op;
const users = await UsersModel.findAll({
  attributes: ['id', 'username', 'password'],
  where: {
    [Op.or]: [
      {id: [4,5]},
      {username: 'John'}
    ]   
  }
});
users[0].password = '105555555'
users[0].save();
console.log(users);

4. not 條件

const Op = Sequelize.Op;
const users = await UsersModel.findAll({
  attributes: ['id', 'username', 'password'],
  where: {
    [Op.not]: [
      {id: [4,5]}
    ]   
  }
});

5. 其他條件 (如果你懂數據庫語言下邊代碼看起來不難

const { Op } = require("sequelize");
Post.findAll({
  where: {
    [Op.and]: [{ a: 5 }, { b: 6 }],            // (a = 5) AND (b = 6)
    [Op.or]: [{ a: 5 }, { b: 6 }],             // (a = 5) OR (b = 6)
    someAttribute: {
      // Basics
      [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)

      // Using dialect specific column identifiers (PG in the following example):
      [Op.col]: 'user.organization_id',        // = "user"."organization_id"

      // Number comparisons
      [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

      // Other operators

      [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' (case insensitive) (PG only)
      [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (PG only)
      [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
      [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
      [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (PG only)
      [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (PG only)

      [Op.any]: [2, 3],                        // ANY ARRAY[2, 3]::INTEGER (PG only)

      // In Postgres, Op.like/Op.iLike/Op.notLike can be combined to Op.any:
      [Op.like]: { [Op.any]: ['cat', 'hat'] }  // LIKE ANY ARRAY['cat', 'hat']

      // There are more postgres-only range operators, see below
    }
  }
});

6. 嵌套條件(一看代碼就懂)

const { Op } = require("sequelize");

Foo.findAll({
  where: {
    rank: {
      [Op.or]: {
        [Op.lt]: 1000,
        [Op.eq]: null
      }
    },
    // rank < 1000 OR rank IS NULL

    {
      createdAt: {
        [Op.lt]: new Date(),
        [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
      }
    },
    // createdAt < [timestamp] AND createdAt > [timestamp]

    {
      [Op.or]: [
        {
          title: {
            [Op.like]: 'Boat%'
          }
        },
        {
          description: {
            [Op.like]: '%boat%'
          }
        }
      ]
    }
    // title LIKE 'Boat%' OR description LIKE '%boat%'
  }
});

第二個例子

Project.findAll({
  where: {
    name: 'Some Project',
    [Op.not]: [
      { id: [1,2,3] },
      {
        description: {
          [Op.like]: 'Hello%'
        }
      }
    ]
  }
});

相當於下邊這個sql語句

SELECT *
FROM `Projects`
WHERE (
  `Projects`.`name` = 'some project'
  AND NOT (
    `Projects`.`id` IN (1,2,3)
    OR
    `Projects`.`description` LIKE 'Hello%'
  )
)

7. 搜索單條記錄

findOne 方法  

const Op = Sequelize.Op;
const user =  await UsersModel.findOne({
  where: {
    username: 'zhangsan'     
  }
})
console.log(user);
console.log(user.id);

8. 獲取數據總數

findAndCountAll 方法

const result = await UsersModel.findAndCountAll();
console.log(result.count);

9. 排序

const users = await UsersModel.findAll({
  attributes: ['id', 'username', 'password'],
  order: [
    ['id', 'DESC']  // 逆序
    // ['id'] 正序
  ]
})
console.log(users[0].username);

10. 分頁

let countPerPage = 2, currentPage = 1;
const users = await UsersModel.findAll({
  attributes: ['id', 'username', 'password'],
  order: [
    ['id', 'DESC']
  ],
  limit: countPerPage, // 每頁多少條
  offset: countPerPage * (currentPage - 1) // 跳過多少條
})
console.log(users);

11. 批量插入

const userCreat =  await UsersModel.bulkCreate([
  {username: 'lisi1', password: '9991'},
  {username: 'lisi2', password: '9992'},
  {username: 'lisi3', password: '9993'},
  {username: 'lisi4', password: '9994'},
  {username: 'lisi5', password: '9995'},
])

12.  更新指定

const Op = Sequelize.Op;
const affectedRows = await UsersModel.update(
  { username: "King" },
  { 
      where: {
        password: '9991'
      } 
  }
);

13.刪除指定

const affectedRows = await UsersModel.destroy(
  { 
    where: {
      password: '9991'
    } 
  }
);

關於統計,關聯查詢與預加載,外鍵等等有時間再補上吧

14. 測試的全部代碼

(async function() {
  const Sequelize = require('sequelize');
  const sequelize = new Sequelize('list', 'root', '123456', {
    host: 'localhost',
    dialect: 'mysql'
  });
  const UsersModel = await sequelize.define('Users', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: Sequelize.INTEGER
    },
    username: {
      type: Sequelize.STRING(20),
      allowNull: false
    },
    password: {
      type: Sequelize.CHAR(32),
      allowNull: false
    },
    createdAt: {
      allowNull: false,
      type: Sequelize.DATE
    },
    updatedAt: {
      allowNull: false,
      type: Sequelize.DATE
    }
  }, {
    tableName: 'users'
  });
  // 單查
  // const Op = Sequelize.Op;
  // const user =  await UsersModel.findOne({
  //   where: {
  //     username: 'zhangsan'     
  //   }
  // })
  // console.log(user.id);
  // 總條數
  // const Op = Sequelize.Op;
  // const result = await UsersModel.findAndCountAll();
  // console.log(result.count);
  // 分頁
  // let countPerPage = 2, currentPage = 1;
  // const users = await UsersModel.findAll({
  //   attributes: ['id', 'username', 'password'],
  //   order: [
  //     ['id', 'DESC']
  //   ],
  //   limit: countPerPage, // 每頁多少條
  //   offset: countPerPage * (currentPage - 1) // 跳過多少條
  // })
  // console.log(users);
  // 批量增
  // const userCreat =  await UsersModel.bulkCreate([
  //   {username: 'lisi1', password: '9991'},
  //   {username: 'lisi2', password: '9992'},
  //   {username: 'lisi3', password: '9993'},
  //   {username: 'lisi4', password: '9994'},
  //   {username: 'lisi5', password: '9995'},
  // ])
  // 更新某條
  // const Op = Sequelize.Op;
  // const affectedRows = await UsersModel.update(
  //   { username: "King" },
  //   { 
  //       where: {
  //         password: '9991'
  //       } 
  //   }
  // );
  // 刪除指定
  // const Op = Sequelize.Op;
  // const affectedRows = await UsersModel.destroy({
  //   where: {
  //     password: '9991'
  //   }
  // });
  // 條件查詢
  // const users = await UsersModel.findAll({
  //   attributes: ['id', 'username', 'password'],
  //   where: {
  //     id: [4,5],
  //     username: 'John'
  //   }
  // });
  // users[0].password = '999999999'
  // users[0].save();
  // const Op = Sequelize.Op;
  // const users = await UsersModel.findAll({
  //   attributes: ['id', 'username', 'password'],
  //   where: {
  //     [Op.or]: [
  //       {id: [4,5]},
  //       {username: 'John'}
  //     ]   
  //   }
  // });
  // users[0].password = '105555555'
  // users[0].save();
  // console.log(users);
  // const Op = Sequelize.Op;
  // const users = await UsersModel.findAll({
  //   attributes: ['id', 'username', 'password'],
  //   where: {
  //     [Op.not]: [
  //       {id: [4,5]}
  //     ]   
  //   }
  // });
  // users[0].password = '105555555'
  // users[0].save();
  // console.log(users);
  // const users = await UsersModel.findAndCountAll();
  // console.log(users.rows);
})()

未完待續。。。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM