-1

如果providect_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

2 回答 2

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
    }
}

或类似的东西。

希望这可以帮助

于 2013-02-12T09:46:40.513 回答
0

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

于 2013-02-12T09:47:32.907 回答