use*_*667 23 node.js sequelize.js
问题摘要:从概念上讲,什么是吸气剂和制定者以及我们为什么要使用它们?
可以在模型上定义"对象属性"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! */ },
}
});
Run Code Online (Sandbox Code Playgroud)
一个具体的例子,而不是"做魔术"将不胜感激!
Jan*_*ier 32
伪属性
将属性,从用户的角度来看似乎是对象的常规属性,但在数据库中不存在.例如,具有名字和姓氏字段的用户对象.然后,您可以创建一个全名设置器:
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
}
}
})
Run Code Online (Sandbox Code Playgroud)
当你有一个用户对象时,你可以做到
console.log(user.fullName)
Run Code Online (Sandbox Code Playgroud)
查看用户的全名.然后在幕后调用getter.
类似地,如果你为全名定义一个setter方法,你可以做到
user.fullName = 'John Doe'
Run Code Online (Sandbox Code Playgroud)
然后将传递的字符串分成两部分并将它们保存在名字和姓氏中.(见上面的简化例子)
保护财产
@ahiipsa已经提供了一个很好的例子.执行user.toJSON()时会调用getter,因此您可以使用getter在将敏感数据发送给用户之前轻松删除它们.
| 归档时间: |
|
| 查看次数: |
20953 次 |
| 最近记录: |