Foreignキーの書き方のメモ
書き方がわからなくなることがよくあるのでメモ。
public function up()
{
Schema::create('users', function (Blueprint $table) {
//id()はbigIncrements(unsignedBigInteger)
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function up()
{
Schema::create('posts', function (Blueprint $table) {
//id()はbigIncrements(unsignedBigInteger)
$table->id();
//userを削除したらpostを削除
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('body');
$table->timestamps();
});
}
パターン1
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
//unsignedBigIntegerを指定
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('post_id');
$table->text('body');
$table->timestamp();
//Postを消したら関連するcommentも削除
$table->foreign('post_id')->references('id')->on('posts')->cascadeOnDelete();
});
}
パターン2
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
//unsignedBigIntegerを指定
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('post_id');
$table->text('body');
$table->timestamp();
//Postを消したら関連するcommentも削除
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});
}
$table->unsignedBigInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts')->cascadeOnDelete();
2行を合併↓ 短く書ける。 foreignIdはunsignedBigIntegerを意味する。
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
パターン3
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
//foreignIdはunsignedBigIntegerを意味する。
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->text('body');
$table->timestamp();
});
}
親テーブルを先に作成する。子のファイルの方が先の場合は参照できないのでエラーが起きる。
コマンド
php artisan migrate:rollback
最新のマイグレーション操作をロールバックする
php artisan migrate:rollback --step=5
stepで最終からいくつのマイグレーション操作をロールバックするか指定。
この場合は最後の5つのマイグレーションをロールバックします。
php artisan migrate:reset
すべてのマイグレーションをロールバックする。
php artisan migrate:refresh
すべてのマイグレーションをロールバックしてから、migrateコマンドを実行します。
php artisan migrate:refresh --step=5
stepオプションを指定し、特定の数のマイグレーションをロールバックしてから再マイグレーション。
この場合は最後の5つのマイグレーションをロールバック、再マイグレーションします。
php artisan migrate:fresh
データベースからすべてのテーブルを削除したあと、migrateコマンドを実行します。