2013-02-12 16 views
-1

我想在表中添加新的记录,如果proudct_id和plan_id已经存在于同一行,那么错误发生,否则保存记录。我写了下面的代码行,但没有成功,如果有任何帮助,所以请,谢谢。我这样做在CakePHP中当你保存新记录时如何检查数据库中已有的记录?

function admin_product_plan_add(){ 

      $exists = $this->ProductPlan->find('all'); 
      $this->set('exists',$exists); 
      foreach ($exists as $exists){ 
      $plan_id = $exists['ProductPlan']['plan_id']; 
      $product_id = $exists['ProductPlan']['product_id']; 


      } 

    $conditions = array('ProductPlan.product_id' => $plan_id, 'ProductPlan.plan_id' => $product_id); 
    $data = $this->ProductPlan->find('all' , array('conditions'=>$conditions)); 
    if (isset($data) && !empty($data)) 
    {   
     echo '<p>User have already add this product plan!</p>'; 
    }else{ 
     if ($this->ProductPlan->save($this->data)){ 

      $this->Session->setFlash('You have successfully add the product plan'); 
      $this->redirect(array('controller' => 'productplans','action' => 'admin_product_plan_list')); 

     } 


    } 

} 

回答

4

使用hasAny()

类似:

public function admin_product_plan_add(){ 
    if($this->ProductPlan->hasAny(array("product_id" => $this->data['ProductPlan']['product_id'],'plan_id' => $this->data['ProductPlan']['plan_id']))){ 
     // USER ALREADY HAVE THIS PRODUCTPLAN 
    } else { 
     //CREATE NEW PRODUCTPLAN 
    } 
} 

或类似的东西。

希望这会有帮助

+0

感谢主席:),它的工作,低调提出这个问题的人不知道hasany()。 – 2013-02-12 09:55:45

0

一个解决方案是在这两行上使用uniq索引。所以当有人试图在这两行上添加另一行时,mysql会抛出一个错误,并且数据不会被插入。

相关问题