Achieve Single Table Inheritance with Sequelize

人走茶凉 提交于 2020-01-05 03:06:53

问题


Is there a way to use sequelize to create single table inheritance?

I would like to have a STI for a Purchase and PartialPurchase model where I would have a type field which would be "Purchase" or "PartialPurchase" and classes Purchase and PartialPurchase which would each inherit from an Operation class.

I don't see this as supported by sequelize, but is an implementation possible?


回答1:


Hey so I know you didn't get an answer to this, in a reasonable time, but you can use a type column that's an enum in your db like you said and then use sequelize's scope feature. Scope's work in everything from queries to model definitions and associations. It works out pretty well. I implemented something similar for a messages table with requests and responses.

module.exports = function(sequelize, DataTypes) {
  var Message = sequelize.define('Message', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER,
    },
    type: {
      type: DataTypes.ENUM('REQUEST', 'RESPONSE', 'FILE'),
      allowNull: false
    },
    text: {
      type: DataTypes.TEXT,
      allowNull: false,
    },
    state: {
      type: DataTypes.JSONB,
      allowNull: true,
    },
    userTeamId: {
      type: DataTypes.INTEGER,
      allowNull: false,
    }
  }, );
  Message.associate = (models) => {
    Message.belongsTo(models.UserTeam, { foreignKey: 'userTeamId', targetKey: 'tag'})
  }
  return Message;
};

And then this is how I do associations.

module.exports = function(sequelize, DataTypes) {
  var UserTeam = sequelize.define('UserTeam', {
    tag: { type: DataTypes.UUID, allowNull: false, unique: true},
    active: { type: DataTypes.BOOLEAN, defaultValue: false },
    activationNonce: { type: DataTypes.STRING },
    UserId: { type: DataTypes.INTEGER, },
    TeamId: { type: DataTypes.INTEGER, },
    type: DataTypes.ENUM('OWNER', 'ADMIN', 'MEMBER', 'GUEST'),
  },);
  UserTeam.associate = (models) => {
    UserTeam.hasMany(models.Message, { as: 'responses', foreignKey: 'userTeamId', sourceKey: 'tag', scope: {type: 'RESPONSE'}})
    UserTeam.hasMany(models.Message, { as: 'requests', foreignKey: 'userTeamId', sourceKey: 'tag', scope: {type: 'REQUEST'}})
    UserTeam.hasMany(models.Message, { as: 'files', foreignKey: 'userTeamId', sourceKey: 'tag', scope: {type: 'FILE'}})
    UserTeam.hasOne(models.Team, {foreignKey: 'id', sourceKey: 'TeamId'})
    UserTeam.belongsTo(models.User, {foreignKey: 'UserId', sourceKey: 'id'})
  }
  return UserTeam;
};

The nice thing about the associations is with that you can do things with an instance of UserTeam like 'userteam.getFiles()' to get all associated files.



来源:https://stackoverflow.com/questions/48438938/achieve-single-table-inheritance-with-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!