我有一个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页似乎建议仅在模型文件中定义关联...
研究