【问题标题】:Issue with simple query in cakePhpcakePhp 中的简单查询问题
【发布时间】:2019-11-06 18:33:00
【问题描述】:

我正在学习CakePhp,我仍然锁定这个问题,可能真的很容易。 我只想在我的数据库中增加一个值(计数)。

我通过 bake 生成代码,一切正常,但我想对其进行调整以制作一个完整的应用程序。

另一个问题,在控制器中还是在模型中更好?我有点迷茫

在 StockController.php 中:

public function increment($id = null){
        $this->Stock->updateAll(
            array('Stock.count' => 'Stock.count + 1'),
            array('Stock.id' => $id ));
        $this->Flash->success(__('stock count +1.'));
        return $this->redirect(['action' => 'index']);
    }

我收到 500 错误消息

【问题讨论】:

  • 请启用调试模式并使用您遇到的错误更新问题。

标签: cakephp controller


【解决方案1】:

在 CakePHP 中有两种模型对象:

  • Table Objects - 提供对存储在特定表中的实体集合的访问权限
  • Entities - 表对象中的一行

对于您的 StockController $this->Stock 似乎是您的表对象。要更改(或增加)单个实体,您需要先获取此实体然后保存:

public function increment ($id = null) {
    // Get Entity + increment count
    $entity = $this->Stock->get($id);
    $entity->count = $entity->count++;

    // Then you need to save your Entity using the Table Object
    if ($this->Stock->save($entity)) {
        $this->Flash->success(__('Stock count +1.'));
        return $this->redirect(['action' => 'index']);
    }

    // If save fails
    $this->Flash->error(__('Stock increment failed :('));
}

我会在控制器中对您的数据进行小幅更改,如果您必须更新和修改更复杂的数据,我会在您的实体或表格对象中的方法上创建 Setters。

编码愉快!

【讨论】:

  • 需要注意的是这个方法不是事务安全的!
  • 非常感谢您的解决方案+解释,只是一个注释:$entity->count = $entity->count+1; (因为++不起作用)
猜你喜欢
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多