如何在ES6类中扩展Sequelize 4 Model?

时间:2018-09-14 06:11:58

标签: node.js sequelize.js

我想创建一个扩展Sequelize Model的类,如下所示

const Sequelize = require('sequelize');

class MyModel extends Sequelize.Model {
   constructor(){
     super()
   }

}

但是我需要知道如何为此MyModel定义/初始化表名和属性。我希望将Sequelize.Model的每种方法都转换为MyModel

1 个答案:

答案 0 :(得分:2)

您可以这样做

定义模型=>

const Sequelize = require("sequelize");
class MyModel extends Sequelize.Model {
  static init(sequelize, DataTypes) {
    return super.init(
      {
        myField: DataTypes.STRING
      },
      { sequelize }
    );
  }
}

并定义关联

const Sequelize = require("sequelize");
class MyModel extends Sequelize.Model {
  static associate(models) {
    this.myAssociation = this.belongsTo(models.OtherModel);
    // or
    this.myAssociation = models.MyModel.belongsTo(models.OtherModel);
  }
}

您可以这样使用它,以获取更多详细信息,请访问this博客。我在这里用过