我在 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 的行会更新。
请帮我