Employeeモデル
php
1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Employee extends Model 8{ 9 // 10 protected $fillable = ['name', 'sex', 'dept_id']; 11}
Deptモデル
php
1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Dept extends Model 8{ 9 // 10 protected $fillable = ['dept_cd', 'dept_name']; 11}
emplyoeesテーブルの設定
php
1<?php 2 3use Illuminate\Support\Facades\Schema; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Database\Migrations\Migration; 6 7class CreateEmployeesTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('employees', function (Blueprint $table) { 17 $table->bigIncrements('id'); 18 $table->string('name'); 19 $table->smallInteger('sex'); 20 $table->bigInteger('dept_id')->unsigned(); 21 $table->timestamps(); 22 $table 23 ->foreign('dept_id') 24 ->references('id') 25 ->on('depts'); 26 }); 27 } 28 29 /** 30 * Reverse the migrations. 31 * 32 * @return void 33 */ 34 public function down() 35 { 36 Schema::dropIfExists('employees'); 37 } 38} 39
deptsテーブルの設定
php
1<?php 2 3use Illuminate\Support\Facades\Schema; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Database\Migrations\Migration; 6 7class CreateDeptsTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('depts', function (Blueprint $table) { 17 $table->bigIncrements('id'); 18 $table->string('dept_cd'); 19 $table->string('dept_name'); 20 }); 21 } 22 23 /** 24 * Reverse the migrations. 25 * 26 * @return void 27 */ 28 public function down() 29 { 30 Schema::dropIfExists('depts'); 31 } 32}
問題点
php artisan tinker を使用して
employeesテーブルに値を入れるときにエラー出ます。
terminal
1App\Employee::create([ 2'name' => 'Eric Clapton', 3'sex' => 1, 4'dept_id' => 1, 5]);
error
1Illuminate/Database/QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 19 foreign key constraint failed (SQL: insert into "employees" ("name", "sex", "dept_id", "updated_at", "created_at") values (Eric Clapton, 1, 1, 2019-06-03 16:18:48, 2019-06-03 16:18:48))'
実現したいこと
まだmodelクラスにはhasMany()やbelongsTo()を追加していませんが、エラー解消後テストとしてblade.phpの画面でLravelの特性を活かし、以下の実行でdept_nameを取得したいです。
App\Employee::all();
試したこと
下記のサイトを参考にして修正したのが提示したテーブルとモデルです。
リンク内容
初めは外部キーを「dept_cd」 にしていたのでそれが問題かと思い、「dept_id」に変更しました。
すると連番(bigIncrements)を外部キーの参照先にするには->unsigned();にして型をbigIntegerにしなければいけないと言われたので変更しましたがダメです。
テーブル作成の順番も変更しましたがダメです。会社のPCでハマり、記載のコードは自宅のPCで試したものですが進展なしです。完全にハマってしまいました。
どなたかよろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/05 00:51