问题摘要:概念上,什么是getter和setter,为什么要使用它们?
http://docs.sequelizejs.com/en/latest/docs/models-definition/?highlight=getterMethods#getters-setters摘录
可以在模型上定义“object-property”getter和setter函数,这些函数既可用于“保护”映射到数据库字段的属性,也可用于定义“伪”属性。
我还在为下面的示例代码而挣扎。我们似乎两次设置“标题”。“v”的论点是什么?
见下文:
var Foo = sequelize.define('Foo', {
title: {
type : Sequelize.STRING,
allowNull: false,
}
}, {
getterMethods : {
title : function() { /* do your magic here and return something! */ },
title_slug : function() { return slugify(this.title); }
},
setterMethods : {
title : function(v) { /* do your magic with the input here! */ },
}
});--一个具体的例子,而不是“做魔术”,将不胜感激!
发布于 2014-02-24 13:27:08
伪性质
从用户的角度来看,这些属性似乎是对象的常规属性,但在数据库中不存在。例如,具有名称和姓氏字段的用户对象。然后,您可以创建一个全名设置程序:
var foo = sequelize.define('foo', {
..
}, {
getterMethods: {
fullName: function () {
return this.getDataValue('firstName') + ' ' + this.getDataValue('lastName')
}
},
setterMethods: {
fullName: function (value) {
var parts = value.split(' ')
this.setDataValue('lastName', parts[parts.length-1])
this.setDataValue('firstName', parts[0]) // this of course does not work if the user has several first names
}
}
})当您有一个用户对象时,您可以简单地这样做。
console.log(user.fullName) 查看用户的全名。然后在幕后调用getter。
类似地,如果为全名定义setter方法,则可以这样做。
user.fullName = 'John Doe'然后将传递的字符串拆分为两个部分,并将它们保存在名字和姓氏中。(见上文简化的示例)
保护特性
@ahiipsa已经提供了一个很好的例子。在执行user.toJSON()时调用getter,因此在将敏感数据发送给用户之前,可以使用Getters轻松地删除敏感数据。
发布于 2020-10-28 05:42:58
@Column({
type: DataType.STRING,
set : function (this: User, value: string) {
this.setDataValue("password", cryptService.hashSync(value));
}
})
password: string;
This is the snippet which is used to store hashed password in database in
place of normal string.https://stackoverflow.com/questions/21949554
复制相似问题