PostgreSQL - 删除帖子时删除所有帖子反应?

时间:2021-04-14 04:44:57

标签: sql postgresql graphql

由于外键将 post.idpost_reaction.post_id 相关联,我无法删除有反应(喜欢)的帖子。

我想在删除时使用 CASCADE 创建一个外键,但是因为一个帖子可以有很多 post_reactions,我收到一个错误:no unique constraint matching given keys for referenced table "post_reactions"

我不应该认为我必须在客户端单独删除所有内容,对吗?即先删除所有 post_reactions,然后删除帖子?

  const handleDeletePost = () => {
    if (postImageRelayId) {
      ImageDeleteMutation(postImageRelayId); // if there is an image, delete it
    }
    if (postReactions.length) {
      PostReactionDeleteMutation(postReactions); // if there are reactions, delete all of them
    }
    PostDeleteMutation(post.id, currentPerson); // delete post itself
  };

图像表有一个 post_id 列,带有一个指向 post.id 的 fkey

post_reactions 表有一个 post_id 列,也有一个指向 post.id 的 fkey

我想简单地从帖子表中删除帖子,并且 postgres CASCADE 删除任何具有该 post_id 的反应和/或图像,但是,我无法在引用 post_reactions 的帖子表上创建外键.post_id

2 个答案:

答案 0 :(得分:1)

外键必须从 post_reactions 指向 posts,而不是相反,因为您的错误消息表明您尝试这样做。

答案 1 :(得分:0)

我误解了 CASCADE。我认为 CASCADE 需要在 post 表上,而不是 post_reactions 表。

我将它添加到 post_reactions_post_id fkey 并且它现在可以工作了。

ALTER TABLE wuddit.post_reactions
    ADD CONSTRAINT post_reactions_post_id_fkey FOREIGN KEY (post_id)
    REFERENCES wuddit.post (id) MATCH SIMPLE
    ON UPDATE NO ACTION 
    ON DELETE CASCADE; // this