前提・実現したいこと
Lravel5.5でCSVからの都道府県と市町村の一括インポート機能をGoodby CSVを用いて実装したいと思っておりますが以下のエラーメッセージが発生し苦慮しております。ご教授のほどよろしくお願い申し上げます。
発生している問題・エラーメッセージ
SQLSTATE[HY000]: General error: 1364 Field 'city_name' doesn't have a default value (SQL: insert into `cities` (`pref_name`) values
該当のソースコード
テーブル構造
php
1<?php 2 3use Illuminate\Support\Facades\Schema; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Database\Migrations\Migration; 6 7class CreateCitiesTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('cities', function (Blueprint $table) { 17 $table->engine = 'InnoDB'; 18 19 $table->increments('id'); 20 $table->string('pref_name'); 21 $table->string('city_name'); 22 $table->timestamps(); 23 }); 24 } 25 26 /** 27 * Reverse the migrations. 28 * 29 * @return void 30 */ 31 public function down() 32 { 33 Schema::dropIfExists('cities'); 34 } 35} 36
CitiesAdminController
php
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\City; 7 8//Csvimport 9use Goodby\CSV\Import\Standard\Lexer; 10use Goodby\CSV\Import\Standard\Interpreter; 11use Goodby\CSV\Import\Standard\LexerConfig; 12 13class CitiesAdminController extends Controller 14{ 15 16 public function showImportCSV() 17 { 18 19 return view('cities/csv'); 20 21 } 22 23 public function importCSV(Request $request) 24 { 25 26 //postで受け取ったcsvファイルデータ 27 $file = $request->file('file'); 28 29 //Goodby CSVのconfig設定 30 $config = new LexerConfig(); 31 $interpreter = new Interpreter(); 32 $lexer = new Lexer($config); 33 34 //CharsetをUTF-8に変換 35 $config->setToCharset("UTF-8"); 36 $config->setFromCharset("sjis-win"); 37 38 $rows = array(); 39 40 $interpreter->addObserver(function(array $row) use (&$rows) { 41 $rows[] = $row; 42 }); 43 44 // CSVデータをパース 45 $lexer->parse($file, $interpreter); 46 47 $data = array(); 48 49 // CSVのデータを配列化 50 foreach ($rows as $key => $value) { 51 52 $arr = array(); 53 54 foreach ($value as $k => $v) { 55 56 switch ($k) { 57 58 case 0: 59 $arr['pref_name'] = $v; 60 break; 61 62 case 1: 63 $arr['city_name'] = $v; 64 break; 65 66 default: 67 break; 68 } 69 70 } 71 72 $data[] = $arr; 73 74 } 75 76 // DBに一括保存 77 City::insert($data); 78 79 return redirect('/admin/cities/')->with('save_message', 'CSVのデータを読み込みました'); 80 81 } 82}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。