在多对多关系中解决DELETE CASCADE

时间:2019-03-07 21:25:13

标签: postgresql

请参阅:SQLFiddle

我正处于多对多的关系:

Broker

我的问题是删除@EntityScan( basePackages = {"com.project1.models"} )

CREATE TABLE IF NOT EXISTS store (
  id BIGSERIAL PRIMARY KEY
);

CREATE TABLE IF NOT EXISTS collection (
  id       BIGSERIAL PRIMARY KEY,
  store_id bigint NOT NULL,
  FOREIGN KEY (store_id) REFERENCES store (id)
    ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS item (
  id       BIGSERIAL PRIMARY KEY,
  store_id bigint NOT NULL,
  FOREIGN KEY (store_id) REFERENCES store (id)
    ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS collection_item (
  id            BIGSERIAL PRIMARY KEY,

  collection_id bigint NOT NULL,
  item_id       bigint,

  UNIQUE (collection_id, item_id),

  FOREIGN KEY (collection_id) REFERENCES collection (id)
    ON DELETE CASCADE,
  FOREIGN KEY (item_id) REFERENCES item (id)
    ON DELETE SET NULL
);

INSERT INTO store (id) VALUES (1);
INSERT INTO item (id, store_id) VALUES (1, 1);
INSERT INTO collection (id, store_id) VALUES (1, 1);
INSERT INTO collection_item (id, collection_id, item_id) VALUES (DEFAULT, 1, 1);

将出现以下错误:

store

我了解问题所在,但我不知道该如何解决。

如果删除DELETE FROM store WHERE store.id = 1; ,则不应删除ERROR: update or delete on table "store" violates foreign key constraint "collection_store_id_fkey" on table "collection" Detail: Key (id)=(1) is still referenced from table "collection". 中的关系,而应将item设置为collection_item。另一方面,如果删除item_id,则还应删除与所有相关的NULL记录。

collection如何在这种设置中工作,或者如果我需要这种行为,我是否必须对表进行建模?

3 个答案:

答案 0 :(得分:0)

您可以将ON DELETE CASCADE添加到ON UPDATE CASCADE

CREATE TABLE IF NOT EXISTS collection (
  id       BIGSERIAL PRIMARY KEY,
  store_id bigint NOT NULL,
  FOREIGN KEY (store_id) REFERENCES store (id)
    ON UPDATE CASCADE
    ON DELETE CASCADE
);


CREATE TABLE IF NOT EXISTS item (
  id       BIGSERIAL PRIMARY KEY,
  store_id bigint NOT NULL,
  FOREIGN KEY (store_id) REFERENCES store (id)
    ON UPDATE CASCADE
    ON DELETE CASCADE
);

SQLFiddle

答案 1 :(得分:0)

要解决此问题,您可以将ON DELETE行为添加到store_id表(以及collection表的)的item列中。基本上,您只需要在这两个表定义中将ON UPDATE更改为ON DELETE,因为我怀疑您将为id表中的现有行更新store列。您还提到了ON DELETE的{​​{1}}列的item_id行为,如果希望在删除collection_item时将列值变成NULL,则可以使用item

ON DELETE SET NULL

答案 2 :(得分:0)

在这种情况下,必须先删除表引用,然后才能删除商店ID。 或进行上述修改。

DELETE FROM item where store_id= 1;

DELETE FROM collection  where store_id = 1;

DELETE FROM store where id = 1;