简体   繁体   English

cakephp中如何从数据库中获取一个值并将修改后的值更新到数据库中?

[英]How to get a value from database and update modified value to database in cakephp?

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.该字段位于 users 表中,其名称为 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.当有人发布某些内容时,应检索与登录用户相关的 no_of_posts 值,然后递增 1 并更新回数据库。

I am trying the following code but its not solving the problem.我正在尝试以下代码,但它没有解决问题。 $userid holds the current users id. $userid 保存当前用户 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.我也尝试使用 find 但它没有用。

$userpost = $this->User->find('count', array('conditions'=>array('User.id'=>$userid)));

Thanks for any help.谢谢你的帮助。

You'll want to look into counterCache.您需要研究一下 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.只要您正确设置了 Post model 和 User model 之间的关系(无论如何您都应该这样做),只要添加几行代码,Cake 就会自动为您跟踪帖子计数。

Check this page in the CakePHP Cookbook: http://book.cakephp.org/1.3/en/view/1033/counterCache-Cache-your-count在 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.除此之外,使用query()方法确实不是 CakePHP 做事的方式。 You should really read the Cookbook pages on Models, because now you're not using CakePHP's full power.您真的应该阅读关于模型的 Cookbook 页面,因为现在您没有使用 CakePHP 的全部功能。 Find the Cookbook pages I mean here: http://book.cakephp.org/1.3/en/view/1000/Models在这里找到食谱页面: http://book.cakephp.org/1.3/en/view/1000/Models

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM