[英]On delete postgres trigger with fkey
我正在使用 postgres 創建一個自身具有 fkey 的表
create table "public"."notes" (
"id" serial not null,
"body" text,
"link" int4,
primary key (id),
constraint "link_key" foreign key (link) references notes(id) on update cascade
);
create or replace function notes_unlink() returns trigger as
$$
begin
update notes set link = null where link = old.id; -- satisfy fkey constraint
return new;
end;
$$
language plpgsql;
create trigger notes_unlink_trigger before delete on notes
for each row execute procedure notes_unlink();
我想要一個刪除觸發器,將“鏈接”注釋設置為 null,以便可以進行刪除。 IE
insert into notes (body, link) values ('foo',null); -- assume id here is 1
insert into notes (body, link) values ('bar',1);
select * from notes;
id | body | link |
----+------+------+
1 | foo | |
2 | bar | 1 |
在嘗試刪除時,例如delete from notes where id = 1;
我希望觸發器將注釋 2.link 設置為 null 並且刪除成功。 我已經嘗試了很多規則和觸發器等,但沒有運氣。 當前發生的情況是,即使在未鏈接的筆記上,刪除也不會刪除任何內容(0 記錄輸出)。
創建外鍵時使用ON DELETE SET NULL
:
ALTER TABLE notes
ADD CONSTRAINT link_key
FOREIGN KEY (link) REFERENCES notes (id)
ON UPDATE CASCADE
ON DELETE SET NULL;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.