MariaDB“ON UPDATE CASCADE”约束未按预期工作?

djmepvbi  于 2023-01-05  发布在  其他
关注(0)|答案(3)|浏览(155)

我期望ON UPDATE CASCADE约束能让我更新被引用的外键的值,并将它级联到它的referee(就像在PostgreSQL中那样),但似乎不是这样。
我错过什么了吗?

  • 此处使用的是玛丽亚数据库10.3.29-玛丽亚数据库-0ubuntu0.20.04.1 *
CREATE TABLE category (
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  parent_id int(11) UNSIGNED DEFAULT NULL,
  slug varchar(255) NOT NULL,
  title varchar(255) NOT NULL,
  content longtext NOT NULL,
  created_at datetime NOT NULL DEFAULT current_timestamp(),
  updated_at datetime DEFAULT NULL,
  CONSTRAINT fk_category_parent_id FOREIGN KEY (parent_id) REFERENCES category (id) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `category` (`id`, `parent_id`, `slug`, `title`, `content`, `created_at`, `updated_at`) VALUES
(1, NULL, 'non-classe', 'Non Classé', '', '2021-05-30 16:46:52', NULL),
(2, NULL, 'cours', 'Cours', '', '2021-05-30 16:47:38', NULL),
(3, 2, 'mysql', 'MySQL', '', '2021-05-30 16:48:18', NULL),
(4, 3, 'initiation-mysql', 'Cours initiation MySQL', '', '2021-05-30 16:49:09', NULL);

UPDATE category SET id = 12 WHERE id = 2;
-- ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cours_cms`.`category`, CONSTRAINT `fk_category_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `category` (`id`) ON UPDATE CASCADE)
rjee0c15

rjee0c151#

参见本页的评论:
https://mariadb.com/kb/en/foreign-keys/
如果ON UPDATE CASCADE递归更新它以前在级联期间更新过的同一个表,则它的作用类似于RESTRICT。这意味着不能使用自引用ON UPDATE CASCADE操作。这是为了防止级联更新导致无限循环。
换句话说,如果表是分层数据类型的表,则ONUPDATE CASCADE不起作用。

c9x0cxw0

c9x0cxw02#

只是确认这在PostgreSQL中工作,没有“无限循环”

CREATE TABLE category (
  id SERIAL PRIMARY KEY,
  parent_id int DEFAULT NULL,
  slug varchar(255) NOT NULL,
  title varchar(255) NOT NULL,
  content text NOT NULL,
  CONSTRAINT fk_category_parent_id FOREIGN KEY (parent_id) REFERENCES category (id) ON DELETE RESTRICT ON UPDATE CASCADE
);

INSERT INTO category (id, parent_id, slug, title, content) VALUES
(1, NULL, 'non-classe', 'Non Classé', ''),
(2, NULL, 'cours', 'Cours', ''),
(3, 2, 'mysql', 'MySQL', ''),
(4, 3, 'initiation-mysql', 'Cours initiation MySQL', '');

UPDATE category SET id=12 WHERE id=2;

SELECT * FROM category;
 id | parent_id |       slug       |         title          | content 
----+-----------+------------------+------------------------+---------
  1 |           | non-classe       | Non Classé             | 
  4 |         3 | initiation-mysql | Cours initiation MySQL | 
 12 |           | cours            | Cours                  | 
  3 |        12 | mysql            | MySQL                  |
mw3dktmi

mw3dktmi3#

这是解决我的问题在laravel代码:
我改了这个

$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade̥');

改为:

$table->foreign('user_id')->references('id')->on('users')->cascadeOnUpdate()->cascadeOnDelete();

相关问题