以下のモデルトテーブル構造があります。
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 12 //belongsTo設定 13 public function dept() 14 { 15 return $this->belongsTo('App\Dept'); 16 } 17}
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 12 //hasMany設定 13 public function employees() 14 { 15 return $this->hasMany('App\Employee'); 16 } 17}
employeesテーブル
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->tinyInteger('sex'); 20 $table->bigInteger('dept_id')->unsigned(); 21 $table->timestamps(); 22 $table->foreign('dept_id')->references('dept_id')->on('depts'); 23 }); 24 } 25 26 /** 27 * Reverse the migrations. 28 * 29 * @return void 30 */ 31 public function down() 32 { 33 Schema::dropIfExists('employees'); 34 } 35} 36
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('dept_id'); 18 $table->string('dept_cd'); 19 $table->string('dept_name'); 20 $table->timestamps(); 21 }); 22 } 23 24 /** 25 * Reverse the migrations. 26 * 27 * @return void 28 */ 29 public function down() 30 { 31 Schema::dropIfExists('depts'); 32 } 33}
問題と現状
まずテーブルをマイグレート時に外部キー制約はきちんとつけられています。(確認済み)
$employees = Employee::all();
を実行し
$employee->dept->dept_name
で部署名を取得しようとすると以下のエラーが出ます。
error
1SQLSTATE[42S22]: Column not found: 1054 Unknown column 'depts.id' in 'where clause' (SQL: select * from `depts` where `depts`.`id` = 1 limit 1)"
調べて分かったこと
おそらくですが、deptメソッドを呼び出すときに自動的に参照先のidという名前を探しにいっているようです。
質問
①このようにmodelで結合させる場合、テーブル先の採番の列は常にidという名前から変更できないのでしょうか。
②①が正しいなら、参照先には常に自動生成のid(bigIncrements)ということになる気がするのですが。
補足
deptテーブルの採番のカラム名を
$table->bigIncrements('id');に変更しemployeesもそれに合わせて表示すると表示はされるようになりました。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。