我有一个我创建的组件:
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']
存在于数据库中。如果它们不存在,我需要将其插入数据库。有谁知道怎么做?