Не работает каскадное удаление sequelize
Когда удаляю в pgadmine юзера, в userRole поля с userId не удаляются
export const User = sequelize.define('user', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: {
args: true,
msg: 'Username already exists. Please try another one.'
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
fullName: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
status: {
type: DataTypes.ENUM(...getEnumValues(UserStatusEnum)),
allowNull: false,
},
organisationId: {
type: DataTypes.INTEGER,
references: {
model: Organisation,
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
}
}, {
hooks: {
beforeRestore: (user, options) => {
user.status = UserStatusEnum.REGISTERED;
},
beforeDestroy: (user, options) => {
user.status = UserStatusEnum.INACTIVE;
}
},
timestamps: true,
paranoid: true
});
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.createTable({schema: process.env.POSTGRES_SCHEMA, tableName: 'userRoles'}, {
id: {
type: Sequelize.DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
userId: {
type: Sequelize.DataTypes.INTEGER,
references: {
model: {
schema: process.env.POSTGRES_SCHEMA,
tableName: 'users'
},
key: 'id'
},
allowNull: false,
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
},
roleId: {
type: Sequelize.DataTypes.INTEGER,
references: {
model: {
schema: process.env.POSTGRES_SCHEMA,
tableName: 'roles'
},
key: 'id'
},
allowNull: false,
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
},
entityType: {
type: Sequelize.DataTypes.STRING,
},
entityId: {
type: Sequelize.DataTypes.INTEGER,
}
}, {transaction});
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.dropTable({
schema: process.env.POSTGRES_SCHEMA,
tableName: 'userRoles'
}, {transaction});
});
}
};
Assotiations
Role.belongsToMany(Permission, {through: RolePermission});
Role.belongsToMany(User, {through: UserRole});
Role.hasMany(UserRole);
UserRole.belongsTo(Role);
UserRole.belongsTo(User);
User.hasMany(UserRole, {onDelete: 'CASCADE', foreignKey: 'userId', hooks: true});
User.belongsToMany(Role, {through: UserRole});
User.belongsTo(Organisation);