简体   繁体   English

如何在 Node.JS 中向 sequelize.js 添加自定义函数?

[英]How to add custom function to sequelize.js in Node.JS?

For example I have a Client model.例如,我有一个 Client 模型。 I want to add new function "sendEmail"我想添加新功能“sendEmail”

The function needs to work send email to one client, or to send email to many clients at once?该功能需要向一个客户端发送电子邮件,还是一次向多个客户端发送电子邮件?

Where to define those functions?在哪里定义这些功能?

Version 4 of sequelize has changed this and the other solutions with instanceMethods and classMethods do not work anymore. sequelize 的第 4 版改变了这一点,其他带有instanceMethodsclassMethods解决方案不再起作用。 See Upgrade to V4 / Breaking changes请参阅升级到 V4 / 重大更改

The new way of doing it is as follows:新的做法如下:

const Model = sequelize.define('Model', {
    ...
});

// Class Method
Model.myCustomQuery = function (param, param2) {  };

// Instance Method
Model.prototype.myCustomSetter = function (param, param2) {  }

Use instanceMethods as Jan Meier pointed out.正如Jan Meier指出的那样,使用instanceMethods

In your client sample:在您的客户示例中:

// models/Client.js
'use strict';

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('Client', {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
  }, {
    instanceMethods: {
      getFullName: function() {
        return this.first_name + ' ' + this.last_name;
      }
    }
  });
};

https://sequelize.org/v4/manual/tutorial/upgrade-to-v4.html#config-options https://sequelize.org/v4/manual/tutorial/upgrade-to-v4.html#config-options

Removed classMethods and instanceMethods options from sequelize.define .sequelize.define删除了classMethodsinstanceMethods选项。 Sequelize models are now ES6 classes. Sequelize 模型现在是 ES6 类。 You can set class / instance level methods like this您可以像这样设置类/实例级方法

Old老的

const Model = sequelize.define('Model', {
    ...
}, {
    classMethods: {
        associate: function (model) {...}
    },
    instanceMethods: {
        someMethod: function () { ...}
    }
});

New新的

const Model = sequelize.define('Model', {
    ...
});

// Class Method
Model.associate = function (models) {
    ...associate the models
};

// Instance Method
Model.prototype.someMethod = function () {..}

I had the same problem, for me it worked to add the method in the classMethods object我遇到了同样的问题,对我来说,在classMethods对象中添加方法是classMethods

// models/Client.js
'use strict';

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('Client', {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
  }, {
    classMethods: {
      getFullName: function() {
        return this.first_name + ' ' + this.last_name;
      }
    }
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM