1

我有一个我创建的组件:

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我需要检查来自 CSV 的值是否$model['order_values']存在于数据库中。如果它们不存在,我需要将其插入数据库。有谁知道怎么做?

4

1 回答 1

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

}
?>
于 2013-07-02T10:42:03.307 回答