PHP,MySQL,类别和子类别–删除

问题描述 投票:1回答:4

我有一个这样的MySQL表:

CREATE TABLE categories (
    ID INT NOT NULL,
    Name VARCHAR(100) NULL,
    Parent INT NULL,
    PRIMARY KEY (ID)
) Engine=InnoDB

我希望确保每当父母被删除时就删除所有孩子。首先,我想通过在表中添加类似的外键来做到这一点:

ALTER TABLE categories ADD CONSTRAINT FOREIGN KEY Parent(Parent) 
REFERENCES categories(ID) ON DELETE CASCADE

这不起作用。我也尝试过内部关系,但没有成功。

父母及其子女与递归PHP函数链接在一起。 MySQL中有没有一种方法可以实现该目标,还是应该使用PHP来完成?

php mysql categories cascading-deletes
4个回答
1
投票

为我工作。

#Server version: 5.1.42-community MySQL Community Server (GPL)
create table lists(
   id int not null
  ,parent int
  ,primary key(id)
  ,foreign key(parent) references lists(id) on delete cascade
) Engine=InnoDb;

insert into lists(id, parent) values(1, null);
insert into lists(id, parent) values(2, 1);
insert into lists(id, parent) values(3, 2);
insert into lists(id, parent) values(4, 3);

mysql> select * from lists;
+----+--------+
| id | parent |
+----+--------+
|  1 |   NULL |
|  2 |      1 |
|  3 |      2 |
|  4 |      3 |
+----+--------+
4 rows in set (0.00 sec)

mysql>
mysql> delete from lists where id = 1;
Query OK, 1 row affected (0.02 sec)

mysql>
mysql> select * from lists;
Empty set (0.00 sec)

2
投票

您已反过来定义了外键。您应该将其定义为:

ALTER TABLE categories ADD CONSTRAINT FOREIGN KEY (id)
REFERENCES Parent(Parent) ON DELETE CASCADE 

0
投票

您需要这样的东西:

drop table if exists categories;
create table categories
(
cat_id int unsigned not null auto_increment primary key,
name varchar(255) not null,
parent_id int unsigned null,
foreign key (parent_id) references categories(cat_id) on delete cascade
)
engine = innodb;

0
投票

Ronnis,Foo,你是对的。真的行。 :-)

我做错了的事情是通过我的PHP应用程序为第一个父代添加了“ 0”。当然,如果我输入“ 0”(没有父代的ID为“ 0”),那么我违反了外键规则。因此,我要做的就是稍微编辑一下INSERT语句。非常感谢您引起我的注意。谢谢大家!

© www.soinside.com 2019 - 2024. All rights reserved.