sequelize事务回滚
发布于 5 年前 作者 junxing1025 4713 次浏览 来自 问答

本人菜鸡🐔,求教 现有两个表

// 菜单
class Menu extends Model {}

Menu.init({
	id: {
		type: Sequelize.INTEGER,
		primaryKey: true,
		autoIncrement: true
	},
	parentId: {
		type: Sequelize.INTEGER
	},
	name: Sequelize.STRING(200)
}, {
	sequelize,
	freezeTableName: true,
	modelName: 'menu'
})
class Role extends Model {}
// 角色
Role.init({
	id: {
		type: Sequelize.INTEGER,
		primaryKey: true,
		autoIncrement: true
	},
	name: Sequelize.STRING(200)
}, {
	sequelize,
	freezeTableName: true,
	modelName: 'role'
})
// 角色和菜单关联表
class RoleMenu extends Model {}

RoleMenu.init({
	id: {
		type: Sequelize.INTEGER,
		primaryKey: true,
		autoIncrement: true
	}
}, {
	sequelize,
	freezeTableName: true,
	modelName: 'role_menu'
})

Role.belongsToMany(Menu, {
	through: RoleMenu,
	foreignKey: 'roleId'
})

Menu.belongsToMany(Role, {
	through: RoleMenu,
	foreignKey: 'menuId'
})

当执行删除菜单的时候清理关联表,以下为操作,出错后并没有回滚

sequelize.transaction(t => {
        return MenuModel.destroy({
            where: {
                id: req.body.id
            }
        }, {transaction: t}).then(() => {
            return RoleMenuModel.destroy({
                where: {
                    menuId: req.body.id
                }
            }, {transaction: t})
        })
    }).then(result => {
        
    }).catch(e => {
        throw new Error()
    })
2 回复

@liangtongzhuo 好像用法都是对的,我的理解出错了,我再好好琢磨下

回到顶部