我尝试从我的控制器增加一个表记录,但它失败了,我想创建一个添加到篮子的方法,它将插入一个新产品或更新现有产品的数量。 另外我想知道是否有任何书籍或教程(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>
答案 0 :(得分:4)
读取当前值,在PHP级别上递增并更新表很容易出现竞争条件,而是使用表达式添加一个原始SQL片段,在SQL级别增加列值
.when()
另见