3

My likes table is a intermediat table in a many-to-many relationship between posts and users. It has the following fields:

id
post_id
user_id

In my mind, the cleanest way to ensure there are no duplicates is to make the ID a concatenation of post_id and user_id. If this is the best way, the question is:

In postgres, how can I make a field have a default value equal to the concatenation of other two fields?

Octavian Niculescu
  • 1,177
  • 1
  • 3
  • 24
  • You can make a unique constraint across two columns... No need for concatenating anything... – MatBailie Dec 30 '21 at 11:12
  • @MatBailie how? If I set a unique for post and a unique for user, then I can't have multiple post_id or multiple user_id in the table. Is there a way to make a unique constraint for the pair post_id+user_id? – Octavian Niculescu Dec 30 '21 at 11:13
  • Make (post_id, user_id,) a composite primary key, where the primary key is made up of both the post_id and user_id columns. Setting this as the primary key essentially means that the same post/user combination can only appear once in the table and cannot be duplicated. – Abdisamad Khalif Dec 30 '21 at 11:20

0 Answers0