在sequelize中使用.upsert()时,我需要获取插入/更新的记录的id。
现在,.upsert()返回一个布尔值,指示行是创建的还是更新的。
return db.VenueAddress.upsert({
addressId:address.addressId,
venueId: venue.venueId,
street: address.street,
zipCode: address.zipCode,
venueAddressDeletedAt: null
}).then(function(test){
//test returned here as true or false how can i get the inserted id here so i can insert data in other tables using this new id?
});发布于 2018-05-12 07:19:01
我不认为当OP提出这个问题时,返回插入的记录是可用的,但后来它已经用这个PR实现了。从SequelizeV4.32.1开始,您可以传递一个布尔returning作为查询参数,以便在返回包含记录的数组和布尔值之间进行选择,或者只返回一个布尔值来表示是否创建了新记录。
您仍然需要提供要upsert的记录的id,否则将创建一条新记录。
例如:
const [record, created] = await Model.upsert(
{ id: 1, name: 'foo' }, // Record to upsert
{ returning: true } // Return upserted record
);发布于 2016-11-10 00:12:24
我希望upsert返回创建或更新的对象。它没有,因为显然只有PGSQL直接支持它。
所以我创建了一个天真的实现,可能是以一种性能不佳的方式,也可能是在各种竞争条件下,这样做:
Sequelize.Model.prototype.findCreateUpdate = function(findWhereMap, newValuesMap) {
return this.findOrCreate({
where: findWhereMap,
defaults: findWhereMap
})
.spread(function(newObj, created) {
// set:
for(var key in newValuesMap) {
newObj[key] = newValuesMap[key];
}
return newObj.save();
});
};在游戏中尝试创建/更新移动时的用法(人为设计的示例警报!):
models.Game
.findOne({where: {gameId: gameId}})
.then(function(game) {
return db.Move.findCreateUpdate(
{gameId: gameId, moveNum: game.moveNum+1},
{startPos: 'kr4', endPos: 'Kp2'}
);
});发布于 2017-06-24 06:14:04
这是对我有效的方法:
Model.upsert({
title:your title,
desc:your description,
location:your locations
}).then(function (test) {
if(test){
res.status(200);
res.send("Successfully stored");
}else{
res.status(200);
res.send("Successfully inserted");
}
})它将根据您的主键检查db以查找。如果找到,它将更新数据,否则将创建新行/插入到新行中。
https://stackoverflow.com/questions/29063232
复制相似问题