概要
Laravelで標準Auth認証を用いてログイン機能を実装した後に、既存のテーブルにuser_idを追加する場合の方法です。
追加用のマイグレーションファイルを作成
//書き方
$ php artisan make:migration add_カラム名_to_追加先のテーブル名_table --table=追加先のテーブル名
//今回の場合はこんな感じ
$ php artisan make:migration add_user_id_to_memos_table --table=memos
実行するとアプリ名/database/migrations配下に作成したマイグレーションファイルが作成されます。
マイグレーションファイルを編集
出来上がったマイグレーションファイルを見ると↓↓↓な感じのが出来上がっている
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddUserIdToMemosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('memos', function (Blueprint $table) {
//
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('memos', function (Blueprint $table) {
//
});
}
}
ここからUPの部分にuser_idを追加します。
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddUserIdToMemosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('memos', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('memos', function (Blueprint $table) {
//
});
}
}
1)user_idのデータ型をUsersテーブルのidのデータ型と合わせる
→データ型はbigIntなので、bigIntegerで指定します。
※合ってないとマイグレーションコマンドを実行した時にエラーになります
→unsignedは符号なしということ(整数のみで-1とかは登録できないようにするということ)
2)この時に外部キー(userテーブルのidと紐づけること)の設定も行う
→foreignメソッドやreferencesメソッドを用いる
→userが削除された時にmemosテーブルに紐づいているデータも一緒に削除されるようにonDeleteメソッドも用いる
マイグレーションを実行
下記のコマンドを実行するとmemosテーブルにカラムが追加されます。
$ php artisan migrate
各モデルにリレーションを設定する
Userモデル
Userは複数のmemoのデータを持つので、1対多の関係になります。
なのでUserモデルにhasManyの記述をします。(※Mが大文字なので注意)
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
{中略}
public function memos(){
return $this->hasMany('App\Memo');
}
}
Memoモデル
Memoテーブルは1つのmemoに対して1人のUserのデータを持つので、
なのでMemoモデルにbelongToの記述をします。(※Tが大文字なので注意)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Memo extends Model
{
{中略}
public function User(){
return $this->belongsTo('App\User');
}
}
以上となります。