0

I have Posts and Comments and users can "Like" either. I'm using cakePHP.

The Posts and Comments tables each have a 'likes' row on them because I don't want to re-count the likes each time the post / comments are loaded. I have a Likes table too, that contains the IDs (post id, user id) so that I know what users have already 'liked' something.

I was wondering how I would set up this relationship within the models in cakePHP and also how I would update Posts.likes field when at the same time adding a new like into the Likes table.

I've set up Likes to "belongTo" Posts and Comments in the Like Model and at the moment, my LikesController.php looks like this:

public function add(){
...
    if ($this->Like->save($this->request->data)) {
      //like is added to Likes table, now how to add to the "parent" Post or Comment??
    }
...
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Tim
  • 6,986
  • 8
  • 38
  • 57
  • [counter cache](http://book.cakephp.org/1.3/view/1033/counterCache-Cache-your-count) should do exactly what you need out of the box. – Ross Oct 15 '12 at 18:53
  • Thanks @Ross, but how would I implement this? Would I keep the Likes table too? I need to know what users have 'liked' content.. – Tim Oct 15 '12 at 19:54
  • Yes you would need to keep the table. countercache in it's most basic sense works by updating `model_count` every time a record is added or deleted to `model`. – Ross Oct 16 '12 at 08:16

1 Answers1

2

Keep your tables as they are, but add a like_count field to your posts and comments tables.

Also add a comment_count to the posts table.

Then just use CakePHP's counterCache, and it will keep track of the # of likes and comments per post automatically.

Dave
  • 28,833
  • 23
  • 113
  • 183
  • thanks @dave, so adding a new like will automatically update the row on posts? and what data should my like data contain please? – Tim Oct 15 '12 at 20:24
  • 1
    Adding a new Like will update the Post's 'like_count' field. Adding a new Comment will update the Post's 'comment_count' field. It's completely up to you what data you save in your 'likes' table. If you're asking about best practice or looking for suggestions for table structure(s), it's probably best if you ask that in a new question. – Dave Oct 15 '12 at 20:37
  • (Deleting a Like or Comment will also update those fields, so - basically as long as you use CakePHP to add or delete items, it automatically keeps the count for you) – Dave Oct 15 '12 at 20:38
  • hi dave, what I essentially mean is what does the like form need to look like? does it need to just send the foreign id of the associated model? thanks for ur help – Tim Oct 15 '12 at 20:53
  • Tim - please ask unrelated items as a new question(s). – Dave Oct 15 '12 at 20:55