我在CakePHP 2.2.1安装上使用CakeDC的Utils插件的csvUpload行为。
我工作得很好,它正在成功处理一个相当大的csv。但是,我的表/模型中有两个字段被认为是固定的,因为它们基于来自不一致的关联模型的ID。所以我需要通过变量获得这些固定值,这很容易。
所以我的问题是,如何使用csvUpload的固定字段方面?我尝试了以下和许多小变化,这显然不起作用。
public function upload_csv($Id = null) {
$unique_add = 69;
if ( $this->request->is('POST') ) {
$records_count = $this->Model->find( 'count' );
try {
$fixed = array('Model' => array('random_id' => $Id, 'unique_add' => $unique_add));
$this->Model->importCSV($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
} catch (Exception $e) {
$import_errors = $this->Model->getImportErrors();
$this->set( 'import_errors', $import_errors );
$this->Session->setFlash( __('Error Importing') . ' ' . $this->request->data['Model']['CsvFile']['name'] . ', ' . __('column name mismatch.') );
$this->redirect( array('action'=>'import') );
}
$new_records_count = $this->Model->find( 'count' ) - $records_count;
$this->Session->setFlash(__('Successfully imported') . ' ' . $new_records_count . ' records from ' . $this->request->data['Model']['CsvFile']['name'] );
$this->redirect(array('plugin'=>'usermgmt', 'controller'=>'users', 'action'=>'dashboard'));
}
}
任何帮助都会非常感激,因为我在搜索时只发现了一篇关于此行为的帖子...
答案 0 :(得分:2)
我制作了自定义方法来完成同样的任务。在app\Plugin\Utils\Model\Behavior
public function getCSVData(Model &$Model, $file, $fixed = array())
{
$settings = array(
'delimiter' => ',',
'enclosure' => '"',
'hasHeader' => true
);
$this->setup($Model, $settings);
$handle = new SplFileObject($file, 'rb');
$header = $this->_getHeader($Model, $handle);
$db = $Model->getDataSource();
$db->begin($Model);
$saved = array();
$data = array();
$i = 0;
while (($row = $this->_getCSVLine($Model, $handle)) !== false)
{
foreach ($header as $k => $col)
{
// get the data field from Model.field
$col = str_replace('.', '-', trim($col));
if (strpos($col, '.') !== false)
{
list($model,$field) = explode('.', $col);
$data[$i][$model][$field] = (isset($row[$k])) ? $row[$k] : '';
}
else
{
$col = str_replace(' ','_', $col);
$data[$i][$Model->alias][$col] = (isset($row[$k])) ? $row[$k] : '';
}
}
$is_valid_row = false;
foreach($data[$i][$Model->alias] as $col => $value )
{
if(!empty($data[$i][$Model->alias][$col]))
{
$is_valid_row = true;
}
}
if($is_valid_row == true)
{
$i++;
$data = Set::merge($data, $fixed);
}
else
{
unset($data[$i]);
}
}
return $data;
}
你可以使用它来使用它:
$csv_data = $this->Model->getCSVData($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
此处$csv_data
将包含来自csv文件的所有记录的数组,这些记录不为空且每个记录索引中都包含固定字段。
答案 1 :(得分:0)
所以当我告诉Arun时,我回答了我自己的问题并弄明白了。我期待广泛而不是真正地检查我面前的东西。我开始运行一些调试并想出来了。
首先,$ unique_add = 69被视为int,duh。为了将它添加到csv,需要将其视为字符串。所以它就变成了,$ unique_add ='69'。
我无法直接将$ Id的值输入到固定数组中。所以我只需要执行一个简单的查找来获得我需要的值。
$needed_id = $this->Model->find('first', array(
'condition'=>array('Model.id'=>$Id)
)
);
$random_id = $needed_id['Model']['id'];
希望不需要帮助任何人,因为希望没有其他人会犯这个愚蠢的错误。但是还有一个......现在互联网上有不止一篇文章记录了CakeDC Utils插件中固定字段的使用情况。