0

我在 Postgres 中有 2 个表,假设是一对多的Category关系Thread

Category

id   | title | created_at | deleted_at 
-----+-------+------------+-----------

Thread

id   | category_id | title | created_at | deleted_at 
-----+-------------+-------+------------+-----------

我想创建一个触发器:如果我执行软删除Categorydeleted_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_atthread都会更新。我的期望是只有category_id= 1 的行会更新。

请帮我

4

1 回答 1

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;
于 2018-11-09T13:57:57.930 回答