【PostgreSQL】外部参照が設定されているレコードを削除できるようにする制約

外部参照が設定されているレコードを削除しようとすると、次のようなエラーがでる。
update or delete on table "users" violates foreign key constraint "user_histories_domain_id_fkey" on table "user_histories"
「”user_histories_user_id_fkey” FOREIGN KEY (user_id) REFERENCES users(id)」の制約が機能していることで、上記エラーが出ている。
autodeploy-# \d user_histories; Table "public.user_histories" Column | Type | Collation | Nullable | Default -----------+-----------------------------+-----------+----------+---------------------------------------------- id | integer | | not null | nextval('user_histories_id_seq'::regclass) date | timestamp without time zone | | not null | action | character varying(50) | | not null | user_id | integer | | not null | Indexes: "user_histories_pkey" PRIMARY KEY, btree (id) Foreign-key constraints: "user_histories_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) autodeploy-#
なので、次のように外部参照キーの制約を変更する。
# 一度削除 ALTER TABLE user_histories DROP CONSTRAINT user_histories_user_id_fkey; # 新たに追加 ALTER TABLE user_histories ADD CONSTRAINT user_histories_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;