0

Alright, I have been searching and finding very much about this subject, but nothing satisfying.

I want to keep track of who has liked what, not just add a +1 to a table.

I have three tables: posts, comments and likes.

The table design looks like this for the moment

CREATE TABLE IF NOT EXISTS `likes` (
  `like_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `post_id_fk` INT(11),
  `comment_id_fk` INT(11),
  `uid_fk` int(11) NOT NULL,
  `date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
FOREIGN KEY (uid_fk) REFERENCES users(uid),
FOREIGN KEY (post_id_fk) REFERENCES post(post_id),
FOREIGN KEY (comment_id_fk) REFERENCES comments(comments_id),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;

And as you can see i have three different foreign keys, uid_fk for the user uid so i can know who has liked what. And now comes there problem, one foreign key to post_id and one for comments_id.

Mysql won't accept a foreign key if it doesn't exist. if i want to "like" a comment, it won't let be because of the foreign key of post_id_fk.

How to solve this DB mess?

And the AJAX like/delike problem:

I found this jQuery : Changing class of button with AJAX call when i was searching, and it looks simpel and very nice. And i have also follow this http://pluscss.com/tutorials/ajax-like-script-using-php-mysql-jquery tutorial. But I'm having problems combine them.

This is what I'm trying to do:

  1. count the current amount of likes
  2. check if the user have liked it before
  3. give the user the option to like (or delike if previously liked)

with ajax and like.php

Could someone help me with this i would be very thankful!

2
  • You should split this up in two questions Commented Feb 27, 2015 at 16:00
  • Why can't you make foreign keys nullable? If you like post, comment will be null. And vice versa. Commented Feb 27, 2015 at 16:22

1 Answer 1

1

It would be better to separate the tables. Create a post_likes table and comments_likes table. That way not only you're getting rid of your existing problem but the structure is more decoupled and more reusable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.