Tuesday, January 5, 2010

update db insted of insert if entry already exists

Hi all,

I have a simple rating controller, so users can rate each other. I
don't know the reason, but every few days the whole ratings table in
the database is empty. All ratings are lost. Here is my ratings
controller as I use it. There are no other methods or anything else. I
exactly use it this way. I use cake 1.2.

Can you find the bug or do you have any suggestions, how I could solve
the issue. What I want to do is: If the voter has already voted
(rated) the user, the old rating should be updated. Otherwise a new
entry in the db should be made. in other words: If a given voter-
profile pair already exists in the db, update the row, otherwise make
a new entry.

And thats the controller:

<?php
class RatingsController extends AppController {

var $name = 'Ratings';

function beforeFilter(){
parent::beforeFilter();
}

function add($id,$points){
//user tries to rate himself
if($id==$this->auth_user['Profile']['id']){
$this->Session->setFlash(__('You cannot rate
yourself',true),'notice');
}
else{

//check if there is already a rating. If so read it in order to
update instead of insert
$entry=$this->Rating->find('first',array('conditions'=>array
('Rating.profile_id'=>(int)$id,'Rating.voter_id'=>$this->auth_user
['Profile']['id']),'recursive'=>-1));
if(!empty($entry['Rating']['id'])){
$this->Rating->read(null,$entry['Rating']['id']);
}
$this->data['profile_id']=(int)$id;
$this->data['voter_id']=$this->auth_user['Profile']['id'];
$this->data['points']=(int)$points;
if($this->Rating->save($this->data)){
$this->Session->setFlash(__('Your rating has been saved.',
true),'success');
}
else{
$this->Session->setFlash(__('Page not found.', true),'error');
}

}
$this->redirect($this->referer());
}

}
?>

Thanks

Donnerbeil

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

No comments: