当您保存新记录时,如何检查数据库中是否已存在记录?

时间:2013-02-12 09:32:51

标签: php mysql cakephp cakephp-1.3 cakephp-2.0

如果在同一行中已经存在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'));

        }


    }

}

2 个答案:

答案 0 :(得分: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
    }
}

或类似的东西。

希望这有帮助

答案 1 :(得分:0)

一种解决方案是在这两行上使用唯一索引。因此,当有人尝试在这两行中添加具有相同数据的另一行时,mysql会抛出错误并且不会插入数据。