Like and Dislike System for Posts
I want to include a like/dislike system similar to Facebook and so far, I have set the like/dislike columns as a 'text' type. This is so that I can add the id for the user(s) who liked/disliked a post. Would that be the best way of doing it? Also, in addition to the question above, how would I stop a user pressing the like and dislike butto开发者_StackOverflow中文版n again? Since, once a user has liked a post, it should display an unlike/undislike option? A concept/idea would be great of how to do this.
While it's hard to make armchair decisions, here are my ideas:
First, you could have a 'likes' integer column for each post. When a user clicks up and down, have that number increment or decrement. This offers no protection against users clicking multiple times, but it's easy and fast.
Another way would be to have a 'Like' table, with columns post_id, user_id, and score. score can have two values: '1' or '-1'. All 3 columns are integers. When the user clicks 'like', you do an INSERT/UPDATE command on the row with user_id & post_id matching.
Then, to see the final score for a post, you do a SELECT SUM(score) FROM that_table WHERE post_id = ?.
With this second method, if you wanted to see the name of the most recent clicker, you could add a timestamp column and search for the most recent entry.
I would create a table with the following structure:
Table: Likes
- PostId bigint
- UserId bigint
- Like bit(true, false)
Then set PostId and UserId together as the primary key. This will prevent the database from inserting multiple likes/unlikes for the same post.
In your code, check to see if the user/post combination exists and then toggle the bit value if it does or set the bit value to true if it does not.
精彩评论