如何扩展 Sequelize 模型 [英] How to extend Sequelize model

查看:76
本文介绍了如何扩展 Sequelize 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在定义模型后扩展(也许继承)模型以添加钩子和字段?

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

就像这样:

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

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

推荐答案

目前无法实现.但是你可以很容易地让它以相反的方式工作:之前定义你的 mixin 并在你定义模型时使用它:

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

这篇关于如何扩展 Sequelize 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆