删除记录时如何删除文件? [英] How to delete files when a record is deleted?

查看:96
本文介绍了删除记录时如何删除文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子:

CREATE TABLE photo (
    photo_id BIGINT NOT NULL AUTO_INCREMENT,
    property_id BIGINT NOT NULL,
    filename VARCHAR (50) NOT NULL;
    ...
    PRIMARY KEY (photo_id),
    CONSTRAINT photo_fk_property FOREIGN KEY (property_id)
        REFERENCES property (property_id)
        ON DELETE CASCADE
);

从该表中删除一行时,它所引用的文件也应删除.在两种情况下,从该表中删除记录:

When a row from this table is deleted, the file that is referenced by it should be deleted as well. There are two scenarios when records are deleted from this table:

  1. 用户删除一张特定的照片.
  2. 用户删除一个特定的属性对象(例如在房地产属性"中),并且所有引用该属性的照片将由ON DELETE CASCADE自动删除.
  1. User deletes one particular photo.
  2. User deletes one particular property object (as in "real estate property"), and all the photos referencing that property are deleted automatically by ON DELETE CASCADE.

我知道我可以在删除属性之前选择数据库中所有引用的照片,然后将它们连同文件一一删除,但是我正在寻找一种替代解决方案.

I know I can select all the referenced photos in the database before deleting a property and delete them along with their files one by one, but I'm looking for an alternate solution. Is it possible to catch the moment when a record in the photo table is deleted and delete the file automatically, without resigning the CASCADE clause, maybe in a trigger somehow?

推荐答案

您正在寻找删除触发器.请参阅此处,了解类似的问题和&解决方案.可以通过安装 sys_exec 来实现外部操作.

You are looking for a DELETE TRIGGER. See here for a similar Problem & Solution. External action can be achieved via installation of sys_exec.

CREATE TRIGGER foobar
AFTER DELETE ON photo
FOR EACH ROW
BEGIN
   CALL sys_exec(concat('/bin/rm -f ',filename));
END

这篇关于删除记录时如何删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆