简体   繁体   中英

PostgreSQL - delete all post reactions when deleting a post?

I'm having trouble delete post having reactions (likes) because of the foreign key associating the post.id with the post_reaction.post_id .

I'd like to create a foreign key with CASCADE on delete, but because a post can have many post_reactions, I get a an error: no unique constraint matching given keys for referenced table "post_reactions"

I shouldn't think I'd have to delete everything individually on the client side, should I? ie delete all the post_reactions first, then the post?

  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
  };

The image table has a post_id column with an fkey to post.id

The post_reactions table has a post_id column also with an fkey to the post.id

I'd like to simply delete the post from the posts table and postgres CASCADE delete any reaction and / or image having that post_id, but, I'm unable to create a foreign key on the post table referencing post_reactions.post_id .

The foreign key has to point from post_reactions to posts , not the other way around, as your error message suggests you tried to do.

I had misunderstood CASCADE. I thought CASCADE needed to be on the post table not the post_reactions table.

I added it to the post_reactions_post_id fkey and it works now.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM