Postgresql – Accessing old version of referenced table in trigger function – Postgresql

postgresqltrigger

In my database I have a table named "layer" and a table named "grouplayer". The table "layer" is referencing the table "grouplayer" by a foreign key constraint with Cascade DELETE.
I have added a trigger function to the table "layer" which is getting the value of another column of the table "grouplayer" by a SELECT query. The function is working as intended when I delete a row of the table "layer". However if I delete a row of the table "grouplayer", the function doesn't work as the result of the SELECT query is NULL.

CREATE OR REPLACE FUNCTION some_func() RETURNS TRIGGER AS $$
DECLARE 
    pro TEXT;
BEGIN
    SELECT project into pro from grouplayer WHERE id = old.grouplayer_id;
    -- Query = NULL. How can I access project from grouplayer before deleting?

    RETURN NEW;
END
$$  LANGUAGE plpgsql;

I can't access the grouplayer even though I have included the keyword Before in the Create Trigger Statement:

CREATE TRIGGER some_trig BEFORE DELETE ON layer FOR EACH ROW EXECUTE PROCEDURE some_func ()

Best Answer

I didn't look at the code, but obviously the row is deleted from grouplayer before the BEFORE trigger on layer is executed.

Perhaps you can perform the task in a BEFORE trigger on layer.