sequelize.define("aModel", {
text: DataTypes.TEXT
}, {
instanceMethods: {
getme1: function() {
return this.text.toUpperCase();
}
},
getterMethods: {
getme2: function() {
return this.text.toUpperCase();
}
}
});
InstanceMethods和getterMethods似乎完成同样的事情,允许访问虚拟密钥。你为什么要用一个呢?
答案 0 :(得分:3)
使用Model.method()
调用的实例方法,但如果您有一个名为text
的getter方法,则会在执行instance.text
时调用它。类似地,当您执行instance.text = 'something'
时,将使用setter方法。
示例:
var Model = sequelize.define("aModel", {
text: DataTypes.TEXT
}, {
instanceMethods: {
getUpperText: function() {
return this.text.toUpperCase();
}
},
getterMethods: {
text: function() {
// use getDataValue to not enter an infinite loop
// http://docs.sequelizejs.com/en/latest/api/instance/#getdatavaluekey-any
return this.getDataValue('text').toUpperCase();
}
},
setterMethods: {
text: function(text) {
// use setDataValue to not enter an infinite loop
// http://docs.sequelizejs.com/en/latest/api/instance/#setdatavaluekey-value
this.setDataValue('text', text.toLowerCase());
}
}
});
Model.create({
text: 'foo'
}).then(function(instance) {
console.log(instance.getDataValue('text')); // foo
console.log(instance.getUpperText()); // FOO
console.log(instance.text); // FOO
instance.text = 'BAR';
console.log(instance.getDataValue('text')) // bar
console.log(instance.text); // BAR
});