Search code examples
typescriptpostgresqltypeorm

Typeorm/Postgres blog like constraint


im creating a blog where you can like a comment or a post with typeorm and postgres, here is the like entitie:

@Entity()
@Unique(["user", "post", "comment"])
export default class Like {
  @PrimaryGeneratedColumn()
  id: number;

  // @Column()
  // likeCount: number;

  @ManyToOne(() => User, (user) => user.likes, { nullable: false })
  user: User;

  @ManyToOne(() => Post, (post) => post.likes)
  post: Post;

  @ManyToOne(() => Comment, (comment) => comment.likes)
  comment: Comment;

I want to create a constraint where a user can like a comment/post only once, in the code above i tried with unique constraints but its not working, how should i do it? should i create two differents tables, one for like-post and one for like-comment? and how do i keep track of how many likes each comment/post have?

i tried unique constraint but is not working


Solution

  • you can use a unique constraint on the combination of the user_id and comment_id columns, or the combination of the user_id and post_id columns. this will allow a user to like more than one post/comment. and use foreign keys to link likes with posts/comments to ensure they exist in the database