zoukankan      html  css  js  c++  java
  • Sequelize增删改查及批量新增或批量更新(bulkCreate的updateOnDuplicate)等常用接口

    一、查询

      查询分为全部查询数据,根据条件查询,全部查询数据及条数(分页),查询特一数据。

    1、查询全部数据

    history.findAll().then(function(history) {
      console.log(history)
    })

    2、根据条件查询数据

      其中 OP.or 的意思是满足下面 dt 和 name 的任意一个都可以,不需要全部满足。

      这个Op是使用以下语句引人入才能够使用,在很多博客里都没有写明,需要查看官方博客才明了:const Op = sequelize.Op;

    let data = await history.findAll({
      where:{
        [Op.or]: [
          {
            dt:{
              [Op.like]: `%${crb.dt}%`
            }
          },
          {
            name:{
              [Op.like]: `%${crb.name}%`
            }
          }
        ]
      }
    });

      搜索有多个条件可以供使用:

    $and: {a: 5}           // AND (a = 5)
    $or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)
    $gt: 6,                // > 6
    $gte: 6,               // >= 6
    $lt: 10,               // < 10
    $lte: 10,              // <= 10
    $ne: 20,               // != 20
    $eq: 3,                // = 3
    $not: true,            // IS NOT TRUE
    $between: [6, 10],     // BETWEEN 6 AND 10
    $notBetween: [11, 15], // NOT BETWEEN 11 AND 15
    $in: [1, 2],           // IN [1, 2]
    $notIn: [1, 2],        // NOT IN [1, 2]
    $like: '%hat',         // LIKE '%hat'
    $notLike: '%hat'       // NOT LIKE '%hat'
    $iLike: '%hat'         // ILIKE '%hat' (case insensitive) (PG only)
    $notILike: '%hat'      // NOT ILIKE '%hat'  (PG only)
    $like: { $any: ['cat', 'hat']}
                           // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
    $overlap: [1, 2]       // && [1, 2] (PG array overlap operator)
    $contains: [1, 2]      // @> [1, 2] (PG array contains operator)
    $contained: [1, 2]     // <@ [1, 2] (PG array contained by operator)
    $any: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)
    
    $col: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example

    3、根据条件查询数据及条数(分页使用

      下面这个语句查询出来的数据包含了数据总条数,可以用来设置分页。offset是偏移数,limit为每页数量

    let data = await B.m.db.history.findAndCountAll({
      where:{
        name:{
          [Op.like]:`%${crb.name}%`
        },
        status:{
          [Op.in]:crb.status
        }
      },
      order:[
        ['id',crb.sort]
      ],
      offset: (crb.currPage - 1) * (crb.pageSize),
      limit: crb.pageSize,
    });

      返回count为总数,rows为查询的pageSize list数据

    4、查询特定数据

      根据id获得特定的数据。

    let data = await template.findOne({
      where:{
        id: crb.id
      }
    });

    5、查询插入

      不存在 => 插入, 存在 => 不插入

    async function findCreateFind() {
        //默认的:查询的条件,没有就创建,有就不作为           
        let result = await UserList.findCreateFind({
          defaults: {username: 'sjj', password: '123'
        
    },
        where: { username: 'sjj' }
      }); console.log(result); }

      查询是否有username=‘sjj’的用户,没有的话就插入数据,有就不作为

    二、新增数据

      传入需要新增的数据,使用create方法即可

    await history
      .create({
        dt: momentTime,
        username: crb.username,
        mail: crb.mail,
      })

    三、修改数据

      根据id修改数据,需要同时传入数据及数据特征(寻找需要修改的数据)。

    let data = await template.update({
      name: crb.name,
      keyword: crb.keyword,
      owner: crb.owner,
      update_time: momentTime,
      update_commit: crb.update_commit
    },{
      where:{
        id: crb.id
      }
    });

      其实新增和编辑通常都是合在一起写保存接口

      if (crb.id) {
        await model.foods_info.update(crb, {
          where: { id: crb.id }
        })
      } else {
        await model.foods_info.create(crb)
      }
      return ctx.response.body={
        success: true,
        msg: '保存成功'
      }

    四、批量新增或批量更新(bulkCreate的updateOnDuplicate)

      说明:如果id存在,则update,否则insert

      updateOnDuplicate:true

    let obj1 = {
        id:0,
        name: "园区问卷调查"
    };
    
    let obj2 = {
        id:1,
        name: "园区问卷调查ddddddddddddddddddddd"
    };
    
    let obj_list = [obj1, obj2];
    
    uc_survey.bulkCreate(obj_list , {updateOnDuplicate:true}).then(result => {
        result.forEach(item => {
            console.log("item:",item)
        });
    }).catch(err => {
        console.log("err:",err)
    });
  • 相关阅读:
    游戏引擎架构笔记之开篇
    Hacker(六)----黑客藏匿之地--系统进程
    Hacker(五)----黑客专用通道--->端口
    Hacker(四)----查看计算机的IP地址
    Hacker(三)之黑客定位目标---IP
    黑客必备技能
    黑客和骇客
    上海公积金提取办法(外地购房,公积金在上海)
    Python入门-----Windows安装
    Python入门-----介绍
  • 原文地址:https://www.cnblogs.com/goloving/p/13456851.html
Copyright © 2011-2022 走看看