有没有办法扩展(也许继承)模型,以便在定义模型后添加钩子和字段?
这样的事情:
User = sequelize.define("user", {
name: sequelize.String
});
makeStateful(User); // adds state,updated,added fields and some hooks
答案 0 :(得分:5)
目前这是不可能的。但是您可以轻松地使其工作:反过来定义您的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'
})
})