admin管理员组

文章数量:1327443

Is there a way to extend (maybe inherit) model to add hooks and fields after model was defined?

So something like this:

User = sequelize.define("user", {
   name: sequelize.String
});

makeStateful(User); // adds state,updated,added fields and some hooks

Is there a way to extend (maybe inherit) model to add hooks and fields after model was defined?

So something like this:

User = sequelize.define("user", {
   name: sequelize.String
});

makeStateful(User); // adds state,updated,added fields and some hooks
Share Improve this question asked Oct 30, 2013 at 12:24 Plastic RabbitPlastic Rabbit 2,9994 gold badges28 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

this is not possible at the moment. But you could easily make it work the other way around: Define your mixin before and use that when you define the model:

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'
  })
})

本文标签: javascriptHow to extend Sequelize modelStack Overflow