根据文档的update
方法有两个参数 - 第一个是values
将用于执行更新,并且第二个是options
- 所以在您的情况下,这是where
子句。如果只想在单个实例上执行更新,则可以采用两种方法执行更新 - 使用Model.update()
方法,该方法可以一次更新该模型的多个实例,匹配where
子句,或者执行instance.update()
以仅更新单个实例。第一个选项将如下所示:
let updateValues = { name: 'changed name' };
models.Model.update(updateValues, { where: { id: 1 } }).then((result) => {
// here your result is simply an array with number of affected rows
console.log(result);
// [ 1 ]
});
当您只想更新单个实例时,第一个选项不是非常有用。所以这就是为什么有上Sequelize模型实例
let updateValues = { name: 'changed name' };
instance.update(updateValues).then((self) => {
// here self is your instance, but updated
});
执行update()
在你的情况下,如果item
参数是Sequelize模型实例(而不是普通的JavaScript JSON对象)的可能性,你的更新功能可能是这样的
exports.updateItem = function(item){
return item.update(values).then((self) => {
return self;
}).catch(e => {
console.log(e);
});
};
但是,如果item
是不是你想要更新sequelize模型实例但值仅一个普通的对象,它可以通过两种方式来实现 - 第一种是使用Model.update()
(就像你所做的那样),或者第二个是与id = item.id
检索TimesheetItem
,然后如上图所示
exports.updateItem = function(item){
models.TimesheetItem.update(item, { where: { id: item.id } }).then((result) => {
// here result will be [ 1 ], if the id column is unique in your table
// the problem is that you can't return updated instance, you would have to retrieve it from database once again
return result;
}).catch(e => {
console.log(e);
});
};
或者与返回的实例,并在其上进行更新的第二个选项进行instance.update()
exports.updateItem = function(item) {
return models.TimesheetItem.findById(item.id).then((itemInstance) => {
return itemIstance.update(item).then((self) => {
return self;
});
}).catch(e => {
console.log(e);
});
}
不同的是,您不需要创建并返回自己的Promise
- 像update()
这样的续订方法可以自行返回承诺。
精彩的回答,你完美解释。 非常感谢! – troyz