2

I have this simple controller action which works as intended. However a user can save the upvote for the same post multiple times. I would like to have the $data saved to the db only if it doesn't already exist with this post_id and user_id combination.

public function addUpvote($id = null){
    $this->autoRender = false;

    if ($this->request->is('ajax')) {

        $data = [
            'post_id' => $id,
            'user_id' => $this->Auth->user('id'),
            'value' => 1
        ];

    $upVote = $this->Votes->newEntity($data);
    $this->Votes->save($upVote);

    }
}

I tried to do it this way

$data = [
            'post_id' => $id,
            'user_id' => $this->Auth->user('id'),
            'value' => 1
        ];

        $votesTable = TableRegistry::get('Votes');
        $exists = $votesTable->exists($data);

        if(!$exists){
            $upVote = $this->Votes->newEntity($data);
            $this->Votes->save($upVote);
        }

This however doesn't work. The $data doesn't get saved anymore even if I would let the if $exist amount to true.

ndru
  • 83
  • 1
  • 10

1 Answers1

1

I'm not sure why its not saving. Could be validation error as said above.

Do:

$tmp = $this->Votes->save($upVote);
debug($tmp);

To see why save isn't working.

I would then use a validation rule to make sure a user can't vote twice which I believe is the goal. Make one that specifies that a record cannot have the same post_id and user_id combination.

See this post.

By using a validation rule you don't need to worry about checking to see if the record already exists and you can reuse it in other areas where a unique combination of fields might be needed.

Community
  • 1
  • 1