Tim
Tim

Reputation: 7056

Update parent model from child (belongsto) model

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??
    }
...
}

Upvotes: 0

Views: 164

Answers (1)

Dave
Dave

Reputation: 29121

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.

Upvotes: 2

Related Questions