質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Laravel 6

Laravel 6は、オープンソースなPHPのフレームワーク。Webアプリケーションの開発に適しており、バージョン6はLTSです。5.8での向上に加えて、セマンティックバージョニングの採用やLaravel Vaporとのコンパチビリティなどが変更されています。

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

Q&A

0回答

1163閲覧

laravelexcel DBへimport時エラーになる

tamado

総合スコア0

Laravel 6

Laravel 6は、オープンソースなPHPのフレームワーク。Webアプリケーションの開発に適しており、バージョン6はLTSです。5.8での向上に加えて、セマンティックバージョニングの採用やLaravel Vaporとのコンパチビリティなどが変更されています。

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

0グッド

0クリップ

投稿2022/04/27 05:57

編集2022/04/30 00:22

Amazon linux 2 AMI上で、
laravel 6のアプリケーションを作成しています。
DBは、mysql(Ver 15.1 Distrib 10.2.38-MariaDB, for Linux (x86_64) using EditLine wrapper)

やりたいことは、CSVの内容をDBのテーブルにインサートしたいのです。
Maatwebsite/Excel 3.1を導入し、下記のようなコードを書いたのですが、エラーが出てしまいます。
(※ちなみに、windowsのxampp環境では、上手く行っております。)

【エラー内容】

SQLSTATE[HY000]: General error: 1364 Field 'month' doesn't have a default value (SQL: insert into Service_summariesImport (updated_at, created_at) values (2022-04-27 02:47:09, 2022-04-27 02:47:09))_

【インポート用のCSV】

※ExcelのCSV形式で保存。文字コードはUTF-8。ヘッダは無し。

CSV

1202201,900011,900001,111,10,1000000 2202201,900011,900001,112,20,2000000

【ソースコード】

Service_summary.php(モデル)

1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Service_summary extends Model 8{ 9 10 protected $fillable = [ 11 'month', 'hoken_number1', 'hoken_number2','service_code', 'user_number', 'sum', 12 ]; 13}

Service_summariesImport.php(インポート)

1<?php 2 3namespace App\Imports; 4 5use App\Service_summary; 6use Maatwebsite\Excel\Concerns\ToModel; 7 8class Service_summariesImport implements ToModel 9{ 10 /** 11 * @param array $row 12 * 13 * @return \Illuminate\Database\Eloquent\Model|null 14 */ 15 public function model(array $row) 16 { 17 return new Service_summary([ 18 19 'month' => $row[0], 20 'hoken_number1' => $row[1], 21 'hoken_number2' => $row[2], 22 'service_code' => $row[3], 23 'user_number' => $row[4], 24 'sum' => $row[5] 25 ]); 26 } 27}

UploadController.php(コントローラ・抜粋)

1 foreach($_POST['chkbox'] as $value){ 2 // zipファイルを解凍する 3 $zip = new ZipArchive(); 4 $zip_path = $upload_path . DIRECTORY_SEPARATOR . $value; 5 //$zip_path = $upload_path . '\\' . $value; 6 7 $result = $zip->open($zip_path); 8 if($result === TRUE) { 9 10 $zip->setPassword('test'); 11 if($zip->extractTo($extract_path) === TRUE){ 12 13 // csvファイルをDBへ登録する 14 for($i = 0; $i < $zip->numFiles; $i++){ 15 $file_name = $zip->getNameIndex($i); 16 $file_path = $extract_path . DIRECTORY_SEPARATOR . $file_name; 17 $import = new Service_summariesImport(); 18 19 Excel::import($import, $file_path); // インポート用のコード 20 } 21 }

migrationファイル

1<?php 2 3use Illuminate\Database\Migrations\Migration; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Support\Facades\Schema; 6 7class CreateServiceSummariesTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('service_summaries', function (Blueprint $table) { 17 $table->bigIncrements('id'); 18 $table->timestamps(); 19 20 $table->integer('month'); 21 $table->integer('hoken_number1'); 22 $table->integer('hoken_number2'); 23 $table->string('service_code'); 24 $table->integer('user_number'); 25 $table->bigInteger('sum'); 26 }); 27 } 28 29 /** 30 * Reverse the migrations. 31 * 32 * @return void 33 */ 34 public function down() 35 { 36 Schema::dropIfExists('service_summaries'); 37 } 38} 39

【試したこと】

調査し次のような手を打ちましたが、全てうまく行きませんでした。

①migrationファイルで、NGとなるカラム名をNULL許可にした。

 $table->integer('カラム名')->nullable();

 →冒頭エラーは解消されたがDBを見ると、CSVの項目がNULL値でインサートされてしまっている。

②migrationファイルで、NGとなるカラム名にデフォルト値を設定した。

 $table->integer('カラム名')->default(NN);

 →冒頭エラーは解消されたがDBを見ると、CSVの項目が入らず、全てデフォルト値がインサートされている。

③config/database.phpのstrictの値をfalseに設定した。

 →冒頭エラーは解消されたがDBを見ると、全て0の値がインサートされている。

【現在の懸念点】

残る怪しい点としては、
config/excel.phpの中身をどこか変えれば上手く行くような気がしていますが、
検討が付きません。

config/excel.php

1<?php 2 3use Maatwebsite\Excel\Excel; 4 5return [ 6 7 ・・前半部分Exportsは略。 8 9 'imports' => [ 10 11 /* 12 |-------------------------------------------------------------------------- 13 | Read Only 14 |-------------------------------------------------------------------------- 15 | 16 | When dealing with imports, you might only be interested in the 17 | data that the sheet exists. By default we ignore all styles, 18 | however if you want to do some logic based on style data 19 | you can enable it by setting read_only to false. 20 | 21 */ 22 'read_only' => true, 23 24 /* 25 |-------------------------------------------------------------------------- 26 | Ignore Empty 27 |-------------------------------------------------------------------------- 28 | 29 | When dealing with imports, you might be interested in ignoring 30 | rows that have null values or empty strings. By default rows 31 | containing empty strings or empty values are not ignored but can be 32 | ignored by enabling the setting ignore_empty to true. 33 | 34 */ 35 'ignore_empty' => false, 36 37 /* 38 |-------------------------------------------------------------------------- 39 | Heading Row Formatter 40 |-------------------------------------------------------------------------- 41 | 42 | Configure the heading row formatter. 43 | Available options: none|slug|custom 44 | 45 */ 46 'heading_row' => [ 47 'formatter' => 'slug', 48 ], 49 50 /* 51 |-------------------------------------------------------------------------- 52 | CSV Settings 53 |-------------------------------------------------------------------------- 54 | 55 | Configure e.g. delimiter, enclosure and line ending for CSV imports. 56 | 57 */ 58 'csv' => [ 59 'delimiter' => null, 60 'enclosure' => '"', 61 'escape_character' => '\\', 62 'contiguous' => false, 63 'input_encoding' => 'UTF-8', 64 ], 65 66 /* 67 |-------------------------------------------------------------------------- 68 | Worksheet properties 69 |-------------------------------------------------------------------------- 70 | 71 | Configure e.g. default title, creator, subject,... 72 | 73 */ 74 'properties' => [ 75 'creator' => '', 76 'lastModifiedBy' => '', 77 'title' => '', 78 'description' => '', 79 'subject' => '', 80 'keywords' => '', 81 'category' => '', 82 'manager' => '', 83 'company' => '', 84 ], 85 86 ], 87   88・・中間略。 89 90 /* 91 |-------------------------------------------------------------------------- 92 | Transaction Handler 93 |-------------------------------------------------------------------------- 94 | 95 | By default the import is wrapped in a transaction. This is useful 96 | for when an import may fail and you want to retry it. With the 97 | transactions, the previous import gets rolled-back. 98 | 99 | You can disable the transaction handler by setting this to null. 100 | Or you can choose a custom made transaction handler here. 101 | 102 | Supported handlers: null|db 103 | 104 */ 105 'transactions' => [ 106 'handler' => 'db', 107 'db' => [ 108 'connection' => null, 109 ], 110 ], 111 112 'temporary_files' => [ 113 114 /* 115 |-------------------------------------------------------------------------- 116 | Local Temporary Path 117 |-------------------------------------------------------------------------- 118 | 119 | When exporting and importing files, we use a temporary file, before 120 | storing reading or downloading. Here you can customize that path. 121 | 122 */ 123 'local_path' => storage_path('framework/cache/laravel-excel'), 124 125 /* 126 |-------------------------------------------------------------------------- 127 | Remote Temporary Disk 128 |-------------------------------------------------------------------------- 129 | 130 | When dealing with a multi server setup with queues in which you 131 | cannot rely on having a shared local temporary path, you might 132 | want to store the temporary file on a shared disk. During the 133 | queue executing, we'll retrieve the temporary file from that 134 | location instead. When left to null, it will always use 135 | the local path. This setting only has effect when using 136 | in conjunction with queued imports and exports. 137 | 138 */ 139 'remote_disk' => null, 140 'remote_prefix' => null, 141 142 /* 143 |-------------------------------------------------------------------------- 144 | Force Resync 145 |-------------------------------------------------------------------------- 146 | 147 | When dealing with a multi server setup as above, it's possible 148 | for the clean up that occurs after entire queue has been run to only 149 | cleanup the server that the last AfterImportJob runs on. The rest of the server 150 | would still have the local temporary file stored on it. In this case your 151 | local storage limits can be exceeded and future imports won't be processed. 152 | To mitigate this you can set this config value to be true, so that after every 153 | queued chunk is processed the local temporary file is deleted on the server that 154 | processed it. 155 | 156 */ 157 'force_resync_remote' => null, 158 ], 159]; 160

どなたかご教授頂けましたら幸いでございます。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2022/04/27 06:16

CSVファイルを読み込んでどのようにデータを保持しているのか、そこから、データをDB格納するまでのソースコードを示してもらわないと、助言しづらいです。
tamado

2022/04/27 06:41

コメントくださり、恐れ入ります。 ソースコードを追加致しました。
phper.k

2022/04/27 08:04

CSV ファイルの文字コードが UTF-8 かどうかをチェックしましょう
tamado

2022/04/27 09:09

コメントくださり、ありがとうございます。 はい、UTF-8でした。
退会済みユーザー

退会済みユーザー

2022/04/28 00:19

CSVファイルを生成しているのは、Excelで形式を指定した保存なのか、他のプログラムによる出力なのか。差し障りない範囲で、CSVのほんの一部でも掲載していただけないでしょうか。
tamado

2022/04/28 00:32

コメントくださり、ありがとうございます。 Excelで形式を指定した保存です。 CSVの一部を掲載しました。 お忙しい中恐れ入りますが、宜しくお願いします。
phper.k

2022/04/29 16:56

Migrationファイル出しているんだし、 SQLSTATE[HY000]: General error: 1364 Field 'カラム名' doesn't have a default value (SQL: insert into テーブル名 (updated_at, created_at) values (2022-04-27 02:47:09, 2022-04-27 02:47:09))_ カラム名とか濁さず書いてください。
tamado

2022/04/30 00:23

コメントありがとうございます。 濁さずに書きました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問