我在Postgres中有2个表,假设Category
和Thread
具有一对多关系
Category
id | title | created_at | deleted_at
-----+-------+------------+-----------
Thread
id | category_id | title | created_at | deleted_at
-----+-------------+-------+------------+-----------
我想创建一个触发器:如果我在Category
中执行软删除(将deleted_at
从null更新为now()),则Thread
。deleted_at
应该会得到也已更新。
这是我的职能
CREATE OR REPLACE FUNCTION "thread_soft_delete"()
RETURNS trigger
AS $pg1$
BEGIN
UPDATE thread SET deleted_at = NOW()
FROM "category"
WHERE thread.category_id = "category".id;
RETURN NULL;
END;
$pg1$
VOLATILE
LANGUAGE plpgsql;
这里是触发器
CREATE TRIGGER category_delete
AFTER UPDATE ON "category"
FOR EACH ROW
WHEN (OLD.deleted_at IS DISTINCT FROM NEW.deleted_at)
EXECUTE PROCEDURE thread_soft_delete();
当我运行update "category" set deleted_at = now() WHERE id = 1;
时,created_at
中的所有thread
列都会更新。我期望只有category_id
= 1的行要更新。
请帮助我
答案 0 :(得分:0)
您无需在触发函数中引用category
表。只需NEW.id()
就可以了。
CREATE OR REPLACE FUNCTION "thread_soft_delete"()
RETURNS trigger
AS $pg1$
BEGIN
UPDATE thread SET deleted_at = NOW()
WHERE thread.category_id = NEW.id;
RETURN NULL;
END;
$pg1$
VOLATILE
LANGUAGE plpgsql;