使用触发器来维护链接表

时间:2013-12-09 21:18:31

标签: postgresql

我正在考虑使用触发器维护链接表。但是由于外键约束违规,我的初始方法失败了。有没有办法在不禁用约束的情况下解决问题?


CREATE TABLE foo (
  id  SERIAL PRIMARY KEY,
  data TEXT
);
CREATE TABLE bar (
  id  SERIAL PRIMARY KEY,
  data TEXT
);
CREATE TABLE foo_bar_link (
  foo_id     INT NOT NULL REFERENCES foo(id),
  bar_id     INT NOT NULL REFERENCES bar(id),
  UNIQUE (foo_id, bar_id)
);
CREATE OR REPLACE FUNCTION maintain_link()
RETURNS TRIGGER AS
$maintain_link$
DECLARE
  bar_id INT;
BEGIN
  INSERT INTO bar (data) VALUES ('not_important_for_this_example_bar_data') RETURNING id INTO bar_id;
  INSERT INTO foo_bar_link (foo_id, bar_id) VALUES (NEW.id, bar_id);
  RETURN NEW;
END;
$maintain_link$
LANGUAGE plpgsql;

CREATE TRIGGER maintain_link BEFORE INSERT ON foo
    FOR EACH ROW EXECUTE PROCEDURE maintain_link();

这是sqlfiddle

1 个答案:

答案 0 :(得分:1)

使用AFTER插入,因为使用BEFORE插入失败,因为你的foo中的父行还不存在。