繁体   English   中英

使用 fkey 删除 postgres 触发器

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM