Search code examples
sqldatabasedatabase-designforeign-keys

store in a database who's liked something


How should a database store who's liked a certain post?

Should I have a separate table which keeps tracks of all likes, and keeps every like of every post together, storing article_id, user_id, and like/dislike?


Solution

  • You are describing a N-M relationship between users and posts, where each user might ligke serveral posts and each post can be liked by several users.

    I would recommend using a bridge table, with foreign keys refering the posts and users tables.

    In a nutshell, that would look like:

    table: users
        user_id
        name
        ...
    
    table: posts
        post_id
        title
        ...
    
    table: users_like_posts
        user_id       -- foreign key to users(user_id)
        post_id       -- foreign key to posts(post_id)
        like_dislike