2017-07-18 86 views
-2

我想从CSV标题创建数据库表格。 这是我的代码。如何从Laravel 5.4中的数组值创建Mysql表格

//give a path of file 
$path = $request->file->getRealPath(); 
//gives csv header and store in array 
$store = ((((Excel::load($path))->all())->first())->keys())->toArray(); 
return dd(array_values ($store)); 

输出:

array:2 [▼ 
    0 => "title" 
    1 => "description" 
] 

我想创建一个列名的表(标题,描述)如何?

谢谢。

+0

我想通了。以下代码将从CSV或EXCEL文件中获取标题,并从这些标题创建SQL表。 $ path = $ request-> file-> getRealPath(); ();}第一个() - > keys() - > toArray();使用($ data){table_> increment('id'); for($ i = 0; $ i string($ data [$ i]); }); return dd(array_values($ data)); – sdsfdesf

回答

-1

我想通了。以下代码将从CSV或EXCEL文件中获取标题,并从这些标题创建SQL表。

  $path = $request->file->getRealPath(); 
      $data = Excel::load($path)->first()->keys()->toArray(); 

      Schema::connection('mysql')->create('aas', function($table) use($data) { 
      $table->increments('id'); 
      for($i = 0; $i < sizeof($data); $i++) 
      $table->string($data[$i]); 

      }); 

      return dd(array_values ($data)); 
0

听起来像一个坏主意。但如果你真的需要它,你可以这样做:

$data = Excel::load($path)->first()->keys()->toArray(); 

\Schema::connection('mysql')->create('newTable', function($table) use($data) { 
    $table->increments('id'); 
    $table->string($data[0]); 
    $table->string($data[1]); 
}); 
+0

谢谢Alexye。这很有用。 但是,有没有什么办法可以在laravel中从csv或excel头创建表? – sdsfdesf

+0

@sdsfdesf上面的代码将使用上面示例中的标题和描述。如果这些键是字面上的'title'和'description',请显示dd(Excel :: load($ path) - > first() - > toArray())的结果' –

+0

array:2 [▼ 0 =>“标题” 1 =>“说明” ] 我收到了这个回应。 – sdsfdesf