Reputation: 161
I'm trying to create a folder and file system in my database.
And while deleting the folders with the subfolder, it should also delete the corresponding files in the folder from my other table (files_plus). But how can i delete both the folder, it's subfolder and all files contained in the folder and subfolders?
Table: files_plus:
-----------------------------
| id | name | parentid |
-----------------------------
(the "parentid" being the "id" from the folders_plus table.)
Table: folders_plus
I can't think of any way to construct a query for doing so, so how would i manage to do this?
Upvotes: 1
Views: 107
Reputation: 6828
You can add a foreign key constraint and set it on "CASCADE DELETE" like this for the folders_plus
table.
ALTER TABLE `folders_plus`
ADD INDEX `folders_plus_parentid_idx` (`parentid` ASC);
ALTER TABLE `folders_plus`
ADD CONSTRAINT `fk_folders_plus_id_folders_plus_parentid`
FOREIGN KEY (`parentid`)
REFERENCES `folders_plus` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION;
And for the files_plus
table:
ALTER TABLE `files_plus`
ADD INDEX `fk_files_plus_id_folders_plus_parentid_idx` (`parentid` ASC);
ALTER TABLE `files_plus`
ADD CONSTRAINT `fk_files_plus_id_folders_plus_parentid`
FOREIGN KEY (`parentid`)
REFERENCES `folders_plus` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION;
When you delete a parent row, it will also delete all of it's children.
Do make sure that your parentid
column is nullable, and that every top level directory is null. Every parentid that is not null, is required to exist as an id in your folders_plus
table.
PS: Please do note that in order for foreign key constraints to work, your database storage engine should be InnoDB.
Upvotes: 1
Reputation: 1940
Upvotes: 0