Yii插入没有重复

时间:2013-07-01 13:34:49

标签: php yii

我有一个我创建的组件:

class CsvImportAction extends CAction {

public $modelClass;

function run()
    {
       $searchModel = $this->modelClass;
       $model = new CsvImportForm;
       $model->selected_table = $searchModel::model()->tableName(); 
       if(isset($_POST['CsvImportForm']))
         {

           $model->attributes=$_POST['CsvImportForm'];

           if($model->validate())
             {

              $csvFile=CUploadedFile::getInstance($model,'file');  
              $tempLoc=$csvFile->getTempName();
              $handle = fopen($tempLoc, "r");
              $sql = "insert into $model->selected_table ({$model['order_values']}) values";
              while (($data = fgetcsv($handle, 10000, "{$model['delimiters']}", "\"")) !== FALSE) {
   $num = count($data);
   //load data into table
  //load only first three - need to change it to load everything
    $sql .= "(";
            foreach($data as $k=>$v)
            {
                $sql.="'{$v}',";
            }
            $sql .= "),";
              }

fclose($handle);
 $sql = substr_replace($sql ,"",-1);
 $sql = str_replace(",)", ")", $sql);
                $connection=Yii::app()->db;
                $transaction=$connection->beginTransaction();
                    try
                        {

                            $connection->createCommand($sql)->execute();
                            $transaction->commit();

                        }
                        catch(Exception $e) // an exception is raised if a query fails
                         {
                            Utility::disableLog();
                            Utility::setFlashError("There is an error!");
                            Yii::app()->end();
                            $transaction->rollBack();

                         }
                         Utility::setFlashSuccess("Successful import");
                  //$this->redirect(Yii::app()->createUrl("/contacts/admin"));
             }
         }  

       $this->getController()->render("//generic/importcsv",array('model'=>$model));
    }

}

我需要添加public $unique_fields之类的内容,然后检查$model['order_values']$this->unique_fields中是否有相同的字段名称我需要检查来自$model['order_values']的CSV值是否存在在数据库中。如果它们不存在,我需要将其插入数据库中。谁知道怎么做?

1 个答案:

答案 0 :(得分:0)

经过几天的疲惫,我把它解决了。这是我的解决方案:

class CsvImportAction extends CAction {

public $modelClass;
public $uniqueFields;       
function run()
    {
       $searchModel = $this->modelClass;
       $model = new CsvImportForm;
       $model->selected_table = $searchModel::model()->tableName(); 

       if(isset($_POST['CsvImportForm']))
         {

           $model->attributes=$_POST['CsvImportForm'];
           $values_array = explode(",",$model['order_values']);
           foreach($this->uniqueFields as $fields)
           {
               $key[] = array_search($fields, $values_array);
           }
           for($i=0;$i<count($key);$i++)
           {
               $query .= " AND (t.".$this->uniqueFields[$i]."=:\$data".$key[$i].")";
           }
           $query = substr($query,4);
           if($model->validate())
             {

              $csvFile=CUploadedFile::getInstance($model,'file');  
              $tempLoc=$csvFile->getTempName();
              $handle = fopen($tempLoc, "r");
              $sql = "insert into $model->selected_table ({$model['order_values']}) values";
              while (($data = fgetcsv($handle, 10000, "{$model['delimiters']}", "\"")) !== FALSE) {
   $num = count($data);
   foreach($data as $d=>$s)
   {
   $query = str_replace(":\$data".$d,"'".$data[$d]."'",$query);
   }
   //load data into table
   //load only first three - need to change it to load everything
    $sql .= "(";
            foreach($data as $k=>$v)
            {

            if (!$searchModel::model()->exists($query))
            {
                    $sql.="'{$v}',";



              }
            }
            $sql .= "),";
              }
    fclose($handle);
$sql = substr_replace($sql ,"",-1);
$sql = str_replace(",)", ")", $sql);
                $connection=Yii::app()->db;
                $transaction=$connection->beginTransaction();
                    try
                        {

                            $connection->createCommand($sql)->execute();
                            $transaction->commit();

                        }
                        catch(Exception $e) // an exception is raised if a query fails
                         {

                            Utility::disableLog();
                            Utility::setFlashError();
                            $transaction->rollBack();
                            //Yii::app()->end();


                         }
                         if(!$e)
                         {
                         Utility::setFlashSuccess();
                         }
                  //$this->redirect(Yii::app()->createUrl("/contacts/admin"));
             }
         }  

       $this->getController()->render("//generic/importcsv",array('model'=>$model));
    }

}
?>