【问题标题】:How to implement bulk update with sequelize?如何使用 sequelize 实现批量更新?
【发布时间】:2021-03-10 06:36:54
【问题描述】:

我在这里尝试过,但没有得到正确答案,此代码将只更新一条记录,但我必须一次更新具有不同 ID 的多条记录,并且我应该将不同的 ID 作为端点传递给 API。

async function bulkupdate(req,res){

    var i;
    let successCount =0; 
    let errorCount = 0;
    var student = req.body;
    var id = req.params.id;

    const schema = {
        name : {type : "string" , optional : false , max :"100"},
        sem : {type : "number" , optional  : false },
        branch :{type : "string" , optional:false,max:"100"}
    
    }
    for(i=0;i<student.length;i++){
        const v = new validator();
        var result1 = await  v.validate(student[i] , schema);
        if(result1 === true){
            var result = await models.Student.update(student[i],{where :{id:id}});
            successCount++;
             
        }else{
            errorCount++
            return res.send({result1,errorCount,successCount})
            
            
        }
    }
    
    res.status(200).json({        
        successCount:successCount,
        errorCount:errorCount,  
    });
  }

【问题讨论】:

    标签: sequelize.js bulkupdate


    【解决方案1】:

    它更新一条记录,因为 id 的值始终相同, 如果请求正文包含学生 ID,那么您可以使用类似于此的内容

    var result = await models.Student.update(student[i],{where :{id: student[i].id}});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多