有没有办法扩展(可能继承)模型以在定义模型后添加钩子和字段?
所以是这样的:
User = sequelize.define("user", {
name: sequelize.String
});
makeStateful(User); // adds state,updated,added fields and some hooks
有没有办法扩展(可能继承)模型以在定义模型后添加钩子和字段?
所以是这样的:
User = sequelize.define("user", {
name: sequelize.String
});
makeStateful(User); // adds state,updated,added fields and some hooks
目前这是不可能的。但是你可以很容易地让它以相反的方式工作:在定义模型之前定义你的 mixin 并在定义模型时使用它:
var Sequelize = require('sequelize')
, sequelize = new Sequelize('sequelize_test', 'root')
var mixin = {
attributes: {
state: Sequelize.STRING,
added_at: Sequelize.DATE
},
options: {
hooks: {
beforeValidate: function(instance, cb) {
console.log('Validating!!!')
cb()
}
}
}
}
var User = sequelize.define(
'Model'
, Sequelize.Utils._.extend({
username: Sequelize.STRING
}, mixin.attributes)
, Sequelize.Utils._.extend({
instanceMethods: {
foo: function() {
return this.username
}
}
}, mixin.options)
)
User.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(u) {
console.log(u.foo()) // 'foo'
})
})