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.