[英]Sequelize on cascade delete run a function?
I have 2 models MenuItems and Category, with a 1-n relation from category to menuitem.我有 2 个模型 MenuItems 和 Category,从类别到菜单项具有 1-n 关系。 Also, whenever a MenuItem is created, a .jpg file is saved on the server (filename is generated by server, so no need to save it as a column in the database).
此外,无论何时创建 MenuItem,都会在服务器上保存一个 .jpg 文件(文件名由服务器生成,因此无需将其保存为数据库中的列)。 I have
我有
{
onDelete: "cascade"
}
set in the Category assosciation, because if a category is deleted then all the menu items should go with it.在 Category 关联中设置,因为如果删除了一个类别,那么所有菜单项都应该随之而来。 However, this leaves a bunch of unused .jpg files.
但是,这留下了一堆未使用的 .jpg 文件。 Is there any way to delete them when the cascade deletion occurs?
发生级联删除时有没有办法删除它们?
You can add beforeDestroy hook for MenuItems model, like below:您可以为 MenuItems 模型添加 beforeDestroy 钩子,如下所示:
// in menuItemsModel.js
MenuItems.beforeDestroy((instance, options) => {
console.log('MenuItems before destroy hook is triggered')
const imageFileDestination = instance.getDataValue('imageUrlFieldName')
// put your logic to delete .jpg files with destination
fs.unlink(url)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.