简体   繁体   中英

How to extends Sequelize 4 Model in ES6 classes?

I want to make a class which extends Sequelize Model like below

const Sequelize = require('sequelize');

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

}

But I need to know how to define/init table name and attributes for this MyModel. I want every method of Sequelize.Model into MyModel

You can do it like this

To Define Models =>

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

and to define associations

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

You can use it like this for more details follow from this blog. I have used it from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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