如何迁移 sequelize 关联?

How to migrate sequelize association?

我向现有数据库添加了一个新的 table。我在模型中创建关联,并在迁移文件中创建 createTable()db:migratesync() 关联未在数据库中创建。 如何在现有数据库中创建关联 witchout sync({force: true})

模型和迁移:

//new model
module.exports = (sequelize, DataTypes) => {
  return sequelize.define('batchOfDrivers', {
    id:        {
      type:          DataTypes.INTEGER,
      primaryKey:    true,
      autoIncrement: true
    }
  }, {
    freezeTableName: true,
    tableName:       'batch_of_drivers',
    classMethods:    {
      associate: models => {
        models.batchOfDrivers.hasMany(models.drivers, {
          foreignKey: 'batchId',
          onDelete: 'cascade'
        });
      }
    }
  });
};


//migration
module.exports = {
  up: function(sequelize, DataTypes) {
    return [
      sequelize.createTable(
        'batchOfDrivers',
        {
          id: {
            type:          DataTypes.INTEGER,
            primaryKey:    true,
            autoIncrement: true
          }
        }
      )
    ];
  },

  down: function(sequelize, DataTypes) {
    return [
      sequelize.removeTable('batchOfDrivers')
    ];
  }
};

看看umzug 使用它以编程方式执行迁移非常容易

您正在创建的新模型与 'drivers' table 有 hasMany() 关联。 sequelize 中的 has* 方法将外键放在另一个 ('target') table.

在您的例子中,目标 table 已经存在,因此需要使用 ALTER TABLE 语句添加外键。您应该将其添加到您的迁移脚本

    //migration
module.exports = {
up: function(sequelize, DataTypes) {
  return [
    sequelize.createTable(
      'batchOfDrivers',
      {
        id: {
          type:          DataTypes.INTEGER,
          primaryKey:    true,
          autoIncrement: true
        }
      }
    ),
    // This may require 2 ALTER statements or have another syntax, depends on your DB
    sequelize.query('ALTER TABLE drivers ADD batchId INTEGER, ADD FOREIGN KEY batchId REFERENCES batchOfDrivers(id);')
  ];
},  

down: function(sequelize, DataTypes) {
  return [
    sequelize.removeTable('batchOfDrivers'),
    // Again, this ALTER statement is going to vary by DB
    sequelize.query('ALTER TABLE drivers DROP constraint drivers_batchId_fk, DROP column batchId;')
  ];
}

这通常需要您先删除 table。当您强制使用同步方法 .sync({force: true}) 时,它就是这样做的。取决于您使用的数据库。