我正在使用Homestead Vagrant存储数据库...现在我在宅基地中创建了表格,为品牌
mysql> desc brands;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
我有这个表格。
我几年前在线找到了此代码。它可能需要轻微的修改,但概念存在。
在您的数据库播种机文件中,在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;
}