新しいカラムを追加するぞ!外部キーも設定しようmigrationファイルを作成します
- ordersテーブルを編集したuser_idを保存するようにしたい
- updated_user_idはnullを許可したい
しかし、実行時エラーになります
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->foreignId('updated_user_id')->constrained('users')->nullable()->default(null)->after('staff_id')->comment('更新したユーザーID NULLの場合は、顧客が更新した場合');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->dropColumn('updated_user_id');
});
}
};
実行結果
# php artisan migrate
INFO Running migrations.
2024_08_25_154037_add_column_updated_user_id_to_orders_table .................................................................. 1,861ms FAIL
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`database`.`#sql-1_3b`, CONSTRAINT `orders_updated_user_id_foreign` FOREIGN KEY (`updated_user_id`) REFERENCES `users` (`id`)) (Connection: mysql, SQL: alter table `order_sheets` add constraint `order_sheets_updated_user_id_foreign` foreign key (`updated_user_id`) references `users` (`id`))
以下略~
調べたところ、 constrained
の前に nullable
を書かないといけないそうな
実行OK!
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->foreignId('updated_user_id')->nullable()->constrained('users')->default(null)->after('staff_id')->comment('更新したユーザーID NULLの場合は、顧客が更新した場合');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->dropColumn('updated_user_id');
});
}
};
実行結果
# php artisan migrate
INFO Running migrations.
2024_08_25_154037_add_column_updated_user_id_to_orders_table .................................................................. 2,672ms DONE