FOREIGN KEY references same table's column. Can't insert values

五迷三道 提交于 2019-12-05 08:05:49

For all your needs you should take this structure

CREATE TABLE `menus` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) unsigned DEFAULT NULL,
  `label` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  KEY `fk_parent_menu` (`parent_id`),
  CONSTRAINT `fk_parent_menu` FOREIGN KEY (`parent_id`) 
    REFERENCES `menus` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
);

SQL Fiddle DEMO

Demo shows inserting and deleting of a parent node

The magic drop part for all children is done by ON DELETE CASCADE

Typically, you will need to allow the 'root' record to have a null parent - i.e. menus.parent_id should be nullable, and the 'root' menu item will have a null parent_id.

i.e.

Change your DDL to:

 parent_id int(10) NULL

And then you add your root element with NULL as the parent_id

insert into `menus` (id, `label`, parent_id)
VALUES (1, 'label1', null);

Then you are good to go with child elements:

insert into `menus` (id, `label`, parent_id)
VALUES (2, 'subitem1', 1);

etc.

SQL Fiddle here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!