You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
Will Schmid edited this page Aug 31, 2014
·
2 revisions
Create triggers that automatically populate arrays of 1-to-many foreign keys
CREATE OR REPLACEFUNCTIONauthors_books() RETURNS trigger AS
$body$
BEGIN
IF TG_OP !='INSERT' THEN
UPDATE authors
SET books = (
SELECT ARRAY(
SELECT id
FROM books
WHERE author_id =OLD.author_idORDER BY title ASC
)
)
WHERE id =OLD.author_id;
END IF;
UPDATE authors
SET books = (
SELECT ARRAY(
SELECT id
FROM books
WHERE author_id =NEW.author_idORDER BY title ASC
)
)
WHERE id =NEW.author_id;
RETURN null;
END;
$body$
LANGUAGE 'plpgsql';
CREATETRIGGERbook_tr1
AFTER INSERT ORUPDATE OF author_id ORDELETEON books FOR EACH ROW
EXECUTE PROCEDURE authors_books();
TODO: make this function generic so it works for any table