如何更新模型中的方法中的记录,如“Sequelize”中的“节点orm-2”
在orm-2中,只需使用this.save()
var users = db.define('users',
{
id : { type: 'serial', key: true },
username : { type: 'text', size: 25, unique: true, required: true },
balance : { type: 'integer', defaultValue: 0 },
}, {
timestamp: true,
methods: {
addBalance: function (howMany) {
howMany = Math.abs(howMany);
this.balance += howMany;
this.save(function (err) {
console.log("added money to "+this.username+" : "+howMany);
});
}
}
});但现在我还不知道
var wallet = sequelize.define('wallet', {
balance : { type: Sequelize.INTEGER, defaultValue: 0, validate: { min: 0 } }
}, {
timestamps: true,
classMethods: {
addBalance: function (howMany) {
howMany = Math.abs(howMany);
this.balance += howMany;
//UPDATE Or SAVE HERE...
}
}
});它是有简单的命令还是更喜欢其他方法?
发布于 2017-02-15 16:07:44
应该将addBalance方法放在instanceMethods中,而不是在classMethods中,因为您希望对指定模型的单个实例进行操作。
instanceMethods: {
addBalance: function(howMany) {
howMany = Math.abs(howMany);
return this.set('balance', this.get('balance') + howMany).save();
}
}该方法将Promise解析返回到模型的当前实例。
编辑
更好的解决方案是使用instance.increment方法
addBalance: function(howMany) {
howMany = Math.abs(howMany);
return this.increment('balance', { by: howMany });
}它将返回与上述选项相同的选项。
https://stackoverflow.com/questions/42254280
复制相似问题