gpt4 book ai didi

javascript - Sequelize js : update/save in model's method

转载 作者:行者123 更新时间:2023-11-29 23:53:25 32 4
gpt4 key购买 nike

如何在“Sequelize”中更新模型方法(如“node 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);
});
}
}
});

但是在Sequelize中,我还不知道

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...
}
}
});

它有简单的命令还是更喜欢其他方法?

最佳答案

您应该将 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 });
}

它将返回与上述选项相同的结果。

关于javascript - Sequelize js : update/save in model's method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254280/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com