sequelize-cli db:migrate不生成关联表

时间:2020-02-10 15:15:57

标签: node.js sequelize.js sequelize-cli

我有一个User模型(关联的迁移文件由sequelize-cli创建):

'use strict';
module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        dispName: DataTypes.STRING,
        email: DataTypes.STRING,
        phoneNum1: DataTypes.STRING
    }, {});
    User.associate = function (models) { // associations added manually
        User.belongsToMany(models.Role, { through: 'UserRoles', foreignKey: 'userId' });
    };
    return User;
};

这是生成的迁移文件:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      cognitoId: { // modified: was an auto-incrementing integer
        allowNull: false,
        primaryKey: true,
        type: Sequelize.STRING(100)
      },
      dispName: {
        type: Sequelize.STRING(100) // modified: was just plain STRING
      },
      email: {
        type: Sequelize.STRING(100) // modified: was just plain STRING
      },
      phoneNum1: {
        type: Sequelize.STRING(15) // modified: was just plain STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

Role模型(由sequelize-cli创建关联的迁移文件):

'use strict';
module.exports = (sequelize, DataTypes) => {
    const Role = sequelize.define('Role', {
        name: DataTypes.STRING
    }, {});
    Role.associate = function (models) { // associations added manually
        Role.belongsToMany(models.User, { through: 'UserRoles', foreignKey: 'roleId' });
    };
    return Role;
};

这是为Role生成的迁移文件:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Roles', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING(100), // modified: was just plain STRING
        unique: true // Added manually
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Roles');
  }
};

运行sequelize-cli db:migrate时,未创建表UserRoles。为什么呢?

Sequelize手册的Associations页似乎建议仅在模型文件中定义关联...

研究

0 个答案:

没有答案