実現したいこと
laravel で seed 時に外部キー制約でエラーになってしまいます。どなたかご教授いただけないでしょうか。
seeder.php
<?php namespace Database\Seeders; use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; class NotesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('notes')->insert([ [ 'user_id' => 1, 'body' => 'サンプルメモ1', 'is_deleted' => false, 'is_saved' => false, 'created_at' => now(), 'updated_at' => now(), ], [ 'user_id' => 2, 'body' => 'サンプルメモ2', 'is_deleted' => false, 'is_saved' => false, 'created_at' => now(), 'updated_at' => now(), ], ]); } }
マイグレーションファイル
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('notes', function (Blueprint $table) { $table->id(); $table->foreignId('user_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade') ->comment('ユーザーID'); $table->text('body', 16384)->comment('メモ本文'); $table->boolean('is_deleted')->default(false)->comment('削除フラグ'); $table->boolean('is_saved')->default(false)->comment('保存フラグ'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('notes'); } };
エラーメッセージ
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`laravel`.`notes`, CONSTRAINT `notes_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `notes` (`body`, `created_at`, `is_deleted`, `is_saved`, `updated_at`, `user_id`) values (サンプルメモ1, 2023-08-21 09:33:21, 0, 0, 2023-08-21 09:33:21, 1), (サンプルメモ2, 2023-08-21 09:33:21, 0, 0, 2023-08-21 09:33:21, 2)) at vendor/laravel/framework/src/Illuminate/Database/Connection.php:760 756▕ // If an exception occurs when attempting to run a query, we'll format the error 757▕ // message to include the bindings with SQL, which will make this exception a 758▕ // lot more helpful to the developer instead of just the database's errors. 759▕ catch (Exception $e) { ➜ 760▕ throw new QueryException( 761▕ $query, $this->prepareBindings($bindings), $e 762▕ ); 763▕ } 764▕ } +7 vendor frames 8 database/seeders/NotesTableSeeder.php:32 Illuminate\Database\Query\Builder::insert() +23 vendor frames 32 artisan:37 Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
試したこと
- マイグレーションし直してみましたが、変わりありませんでした
- seederに記載したuse_idが存在するか確認しました
- マイグレーションファイルの日付順が正しいか確認しました(userのほうが古い日付でしたので問題なさそうでした)

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。