I have to do a blog assignment. In it I have to update a field when someone adds a post. The field is in users table and its name is no_of_posts. When someone posts something the value of no_of_posts related to the user who is logged in should be retrieved then incremented by 1 and updated back to database.
I am trying the following code but its not solving the problem.
$userid holds the current users id.
$userid = $this->Auth->user('id');
$userpost = $this->User->query("SELECT no_of_posts FROM users WHERE id = '$userid'");
$userpost++;
$this->User->query("UPDATE users SET no_of_posts = '$userpost' WHERE id = '$userid'");
I also tried using find but its of no use.
$userpost = $this->User->find('count', array('conditions'=>array('User.id'=>$userid)));
Thanks for any help.
You’ll want to look into counterCache.
As long as you’ve properly set up the relation between the Post model and the User model (which you should, anyway), Cake keeps track of the post count automatically for you if you just add a few lines of code.
Check this page in the CakePHP Cookbook: http://book.cakephp.org/1.3/en/view/1033/counterCache-Cache-your-count
As for what you’re doing wrong in your example: the query call you do returns an array, so it’s only logical that your update query fails.
Apart from that, using the
query()method really isn’t the CakePHP way of doing things. You should really read the Cookbook pages on Models, because now you’re not using CakePHP’s full power. Find the Cookbook pages I mean here: http://book.cakephp.org/1.3/en/view/1000/Models