create_people_table
php
1<?php 2 3use Illuminate\Support\Facades\Schema; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Database\Migrations\Migration; 6 7class CreatePeopleTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('people', function (Blueprint $table) { 17 $table->increments('id'); 18 $table->string('name'); 19 $table->string('mail'); 20 $table->integer('age'); 21 $table->timestamps(); 22 }); 23 } 24 25 /** 26 * Reverse the migrations. 27 * 28 * @return void 29 */ 30 public function down() 31 { 32 Schema::dropIfExists('people'); 33 } 34} 35
Personモデル
php
1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6use Illuminate\Database\Eloquent\Builder; 7use App\Scopes\ScopePerson; 8 9class Person extends Model 10{ 11 protected $guarded = array('id'); 12 13 public static $rules = array( 14 'name' => 'required', 15 'mail' => 'email', 16 'age' => 'integer|min:0|max:150' 17 ); 18 19 public function getData() 20 { 21 return $this->id . ': ' . $this->name . ' (' . $this->age . ')'; 22 } 23 24 public function boards() 25 { 26 return $this->hasMany('App\Board'); 27 } 28}
create_boards_table
php
1<?php 2 3use Illuminate\Support\Facades\Schema; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Database\Migrations\Migration; 6 7class CreateBoardsTable extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('boards', function (Blueprint $table) { 17 $table->increments('id'); 18 $table->integer('person_id'); 19 $table->string('title'); 20 $table->string('message'); 21 $table->timestamps(); 22 }); 23 } 24 25 /** 26 * Reverse the migrations. 27 * 28 * @return void 29 */ 30 public function down() 31 { 32 Schema::dropIfExists('boards'); 33 } 34}
Boardモデル
php
1<?php 2namespace App; 3 4use Illuminate\Database\Eloquent\Model; 5 6class Board extends Model 7{ 8 protected $guarded = array('id'); 9 10 public static $rules = array( 11 'person_id' => 'required', 12 'title' => 'required', 13 'message' => 'required' 14 ); 15 16 // 新たにメソッドを追加 17 public function person() 18 { 19 return $this->belongsTo('App\Person'); 20 } 21 22 // 既にあるメソッドを修正 23 public function getData() 24 { 25 return $this->id . ': ' . $this->title . ' (' 26 . $this->person->name . ')'; 27 } 28} 29
疑問
これはPersonモデルを主テーブルとして扱っているようです(参考書に従っています)
疑問なのが、外部キー制約を全く記述していないのに、peopleテーブルのidとboardsテーブルのperson_idが紐づけされています。
これはboardsテーブルにpeopleの単数形であるpersonとidをくっつけたperson_idカラムがあるので、Laravelが自動的に判断しているのですか。
今まで触った参考書や学習サイトでは必ず外部キー制約をテーブルにつけていました。
疑問ではなく質問をしてください。
回答1件
あなたの回答
tips
プレビュー