我正在尝试使用 Sequelize 在我的 expressJs 应用程序中添加用于创建数据的函数。
控制器:Campaign.upsert({
institution_id : institution_id,
description : campaign_about
}).then(value => {
InstitutionDetail.create({
institution_id : institution_id,
support_description : support_description,
img_homepage : img_homepage
}).then(value1 => {
var campaign = {};
var obj = {campaign};
obj.campaign = value;
obj.institution_detail = support_description;
obj.institution_img_home = img_homepage;
res.json({
'data': obj
})
}).catch(reason => {
if(value == true){
//if campaign created
Campaign.destroy({force: true, where:{institution_id:institution_id}});
} else {
//if campaign updated
//how to undo the updated, so I can have the previous data back
Campaign.destroy({where:{institution_id:institution_id}});
}
News.destroy({where:{id:value2.id}});
Testimony.destroy({where:{id:value1.id}});
responseUtil.fail(res, reason)
})
}).catch(reason => responseUtil.fail(res, reason))
如果InstitutionDetail中的create
失败,我想销毁Campaign创建的数据,或者如果Campaignupdate
,则取回以前的数据。
如果活动确实create
,我已经使用捕获中的destroy
成功删除了广告系列数据,但我不知道如果广告系列update
该怎么办。
我尝试在模型中使用paranoid
:
timestamps: true,
paranoid: true
并在模型中添加列deletedAt
。
但它只将deletedAt
设置为当前时间,如果Campaign确实update
,它并没有取回数据
根据文档:
返回一个布尔值,该值指示行是创建还是更新。 对于MySQL/MariaDB,它在插入时返回true,在插入时返回false。 更新。对于带有 (options.returning=true( 的 Postgres/MSSQL,它返回 记录并创建带有签名的布尔值。
所以试试:
Campaign.upsert({
institution_id : institution_id,
description : campaign_about
}).then(value => {
console.log(value); // <--- This should return true/false
});
Campaign.upsert({
institution_id : institution_id,
description : campaign_about
},{ returning : true }) // <----- with (options.returning=true)
.then(value => {
console.log(value); // <--- This will return model + created : true/false
});