2015-06-16 46 views
1

我目前正試圖爲我們的應用程序之一實施靈活且易於使用的導入服務。該應用程序在後臺運行Laravel,目前我們正在使用固定的csv-import。
這意味着:客戶需要提供由我們的指南格式化的csv文件,以匹配我們數據庫中的列。如何:在導入到laravel時靈活的數據映射?

現在這工作正常,但肯定不靈活或直觀。

現在我試圖想出一個更好的解決方案(例如像MailChimp使用的csv導入嚮導)。

但目前我完全失去了。我不知道我怎麼會使用一個庫像https://github.com/ddeboer/data-import實現具有以下特點的解決方案:

  • 接受CSV或XLS
  • 讓用戶的地圖是數據,使其符合我們的數據庫列
  • 讓利用戶將多個源列組合到一個目標列中

我的主要挑戰是要由用戶接收數據並讓他們自己選擇映射。如何在使用像ddeboer/data-import這樣的庫時分割這個過程?

還應該考慮到,數據庫可能會在未來幾個月內發生變化,如果可能的話,我不想回到我的源代碼來實現這些更改。

如果有人能指出我真正讚賞的正確方向。

謝謝!

回答

1

我們有如下所示想出瞭解決辦法:

我們與多個路由工作:

1. /import GET
2. /import POST
3. /import-map GET
4. /import-map POST

1)呈現了一個視圖用於上傳csv文件的文件輸入。

2)將文件上傳到臨時路徑,以便我們可以使用它。路徑被保存到會話中並被3)用來打開文件。由於我們必須處理許多不同的編碼,因此上傳函數會執行一些令人討厭的解碼/編碼來獲得有效的utf8文件。

/** 
* Upload the given file to a temp path 
* 
* @param Filesystem $filesystem 
* @param $filePath 
* @return string 
*/ 
public function upload(Filesystem $filesystem, $filePath) 
{ 
    $path = str_random(20); 
    $fullPath = public_path('temp/' . $path . '.csv'); 

    if (! mb_detect_encoding($filesystem->get($filePath), mb_detect_order(), true)) 
     $filesystem->put($filePath, chr(239) . chr(187) . chr(191) . utf8_encode($filesystem->get($filePath))); 

    $filesystem->move($filePath, $fullPath); 

    return $path; 
} 

3)呈現導入映射視圖。該文件使用會話中的值加載。如果沒有找到會話數據,則用戶被重定向到1)。

<th> 
    <select name="col-name[{{ $i }}]" data-eq="{{ $i }}" class="form-control"> 
     <option value="">Datenbankspalte auswählen</option> 
     @foreach($tableColumns as $key => $value) 
      <option value="{{ $key }}">{{ $value }}</option> 
     @endforeach 
    </select> 
</th> 

4)以管理導入的護理:

/** 
* Import the uploaded file one row at a time 
* 
* @param $input 
* @return bool 
* @throws \Exception 
*/ 
public function import(array $input) 
{ 
    if (! array_key_exists('campaign_id', $input)) 
     throw new Exception(); 

    $columns = array_filter($input['col-name']); 

    if (empty($columns)) 
     throw new Exception(); 

    $this->openFile($input['csvPath']); 

    foreach ($this->readCsv(null, (array_key_exists('headers', $input) ? 1 : 0)) as $row) 
    { 
     $address = new $this->address; 

     foreach ($columns as $key => $value) 
     { 
      if ($value == '') 
       continue; 

      $address->$value = $row[$key]; 
     } 
     $address->save(); 
     $address->campaigns() 
       ->attach($input['campaign_id'], ['client_id' => auth()->user()->client_id, 'user_id' => (array_key_exists('user_id', $input) ? $input['user_id'] : 0)]); 
    } 

    return true; 
} 

這是不是太困難,是不是:-)

+0

謝謝你的分享!我真的很想看到表單/導入POST頁面以及:) – cevizmx

+0

究竟哪個部分? '/ import POST'沒有頁面,因爲它只上傳文件並重定向到映射部分。 – Tim

相關問題