【问题标题】:How to check records already exist in database when u save new record?保存新记录时如何检查数据库中已存在的记录?
【发布时间】:2013-02-12 09:32:50
【问题描述】:

如果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'));

        }


    }

}

【问题讨论】:

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


    【解决方案1】:

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

    或类似的东西。

    希望对你有帮助

    【讨论】:

    • 谢谢先生 :),它起作用了,反对这个问题的人不知道 hasany()。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      相关资源
      最近更新 更多