【问题标题】:cakephp 3 increment recordcakephp 3 增量记录
【发布时间】:2015-08-29 13:00:52
【问题描述】:

我尝试从我的控制器增加一个表记录,但它失败了,我想创建一个添加到购物篮的方法,该方法将插入新产品或更新现有产品的数量。 另外我想知道是否有任何书籍或教程(除了来自 cakephp 网站的教程)详细解释了 cakephp。 我是 cakephp 的初学者,看起来很困惑,欢迎和感谢任何帮助。

控制器

我的代码:

>  function add($id = null,$name = null){
>        
>        $addCart = $this->Cart->newEntity();
> 
>        if($this->request->is('Get')){
>           
>           $data1 = $this->Cart->exists(['productId' => $id]);
>         
>         //if product doesn't exist in table then add it
>           if(!$data1){ 
>             $addCart = $this->Cart->patchEntity($addCart,[
>                                                 'productId' => $id,
>                                                 'name' => $name,
>                                                 'productQty' => 1]
>                                                 );
>             if($this->Cart->save($addCart)){
>               $this->Flash->success(__('The product has been saved.'));
>               return $this->redirect(['controller' => 'users','action' => 'index']);
>             }else{
>               $this->Flash->error(__('The product could not be saved. Please, try again.'));
>             }
> 
>           }else{ //if product already exists in table then update quantity
>             $updateQty = $this->Cart->patchEntity($addCart, [
>                                                ['productQty' => 'productQty+1'],
>                                                'conditions' => ['productId' => $id] //update quantity where the product id matches
>                                                ]);
>            if($this->Cart->save($updateQty)){
>               $this->Flash->success(__('The product already exists.Quantity updated'));
>               return $this->redirect(['controller' => 'users','action' => 'index']);
>            }else{
>               $this->Flash->error(__('The product could not be updated. Please, try again.'));
>            }
>           }//end inner if
> 
>        }//end if
>         }//end function

查看

<button class="btn btn-default">
  <?= $this->Html->link('Add Product',['controller' => 'Cart', 'action' => 'add',2,'gpu'])
      //$this->Html->link('Add Product',['controller' => 'Cart', 'action' => 'index'])
  ?>
</button>

【问题讨论】:

    标签: php html cakephp-3.0


    【解决方案1】:

    读取当前值、在 PHP 级别递增和更新表很容易出现竞争条件,而是使用表达式添加原始 SQL sn-p 以在 DB 级别递增列值

    $query = $this->Cart->query();
    $result = $query
        ->update()
        ->set(
            $query->newExpr('productQty = productQty + 1')
        )
        ->where([
            'productId' => $id
        ])
        ->execute();
    

    另见

    【讨论】:

    • 好的,谢谢。在没有 $query->newExpr 的情况下工作。 set([('productQty = productQty + 1')])
    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    相关资源
    最近更新 更多