2017-04-19 103 views
0

我使用宅基地流浪漢存儲數據庫...現在我在我的宅基地作爲品牌導入CSV文件,在宅基地laravel MySQL表的Fileds

mysql> desc brands; 
+-------+--------------+------+-----+---------+----------------+ 
| Field | Type   | Null | Key | Default | Extra   | 
+-------+--------------+------+-----+---------+----------------+ 
| id | int(11)  | NO | PRI | NULL | auto_increment | 
| name | varchar(255) | YES |  | NULL |    | 
+-------+--------------+------+-----+---------+----------------+ 

我有來回此表龐大的數據創建的表。現在我想從excel保存爲.csv格式的表中添加字段,我如何使這成爲可能...

+0

要添加新的字段使用ALTER TABLE語句 - [ALTER TABLE語法(https://dev.mysql.com/doc/refman/5.7/en/alter-table.html)。要從CSV文件加載數據,請使用LOAD DATA INFILE命令 - [LOAD DATA INFILE Syntax](https://dev.mysql.com/doc/refman/5.7/en/load-data.html)。 – Devart

回答

0

我在幾年前的某個地方發現了此代碼。它可能需要稍微修改,但概念在那裏。

在你的數據庫文件播種機,在run()方法:

// path to csv file 
$csvFilename = app_path().'/../database/seeds/csv/filename.csv'; 

// run the seeder and get the variable to store the CSV data array 
$seedData = $this->seedFromCSV($csvFilename, ','); 

// Insert into your table 
DB::table($csvTable)->insert($seedData); 

現在在下面的播種機,確保你的頭名匹配數據庫中的表名。

/** 
* Collect data from a given CSV file and return as array 
* 
* @param $filename 
* @param string $deliminator 
* @return array|bool 
*/ 
private function seedFromCSV($filename, $deliminator = ',') 
{ 

    $header = NULL; 
    $data = array(); 

    if(($handle = fopen($filename, 'r')) !== FALSE) 
    { 
     while(($row = fgetcsv($handle, 1000, $deliminator)) !== FALSE) 
     { 
      if(!$header) { 
       $header = $row; 
      } else { 
       $data[] = array_combine($header, $row); 
      } 

     } 

     fclose($handle); 
    } 

    return $data; 

}