Home > Blockchain >  PostgreSQL many-to-many relationship with some particular constrains
PostgreSQL many-to-many relationship with some particular constrains

Time:03-28

I stumbled across a many-to-many problem. I have three entities: User, UserReaction and Post. Basically an User can react to a Post with a reaction (Like, Dislike etc.). The problem is that the user should react with only one reaction per post.

But with my current database an user can make multiple reacts to a post.

Can I constrain a user to make a single react per post through database or should I treat this in code?

enter image description here

enter image description here

CodePudding user response:

Create a unique constraint:

Alter table UserReaction
      add constraint one_reaction_per_customer_per_post
          unique ( customer_id, post_id); 
      
  • Related