2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel9のマイグレーションの外部制約について

Last updated at Posted at 2022-04-20

エラーが起きた背景

外部キーの制約をし、マイグレーションを実行しました。

Schema::create('folders', function (Blueprint $table){
    $table->increments('id');
    $table->foreign('user_id')->references('id')->on('users');
    $table->string('title');
    $table->timestamps();
    });

すると

 Illuminate\Database\QueryException 

  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'user_id' doesn't exist in table (SQL: alter table `folders` add constraint `folders_user_id_foreign` foreign key (`user_id`) references `users` (`id`))

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:745
    741▕         // If an exception occurs when attempting to run a query, we'll format the error
    742▕         // message to include the bindings with SQL, which will make this exception a
    743▕         // lot more helpful to the developer instead of just the database's errors.
    744▕         catch (Exception $e) {
  ➜ 745▕             throw new QueryException(
    746▕                 $query, $this->prepareBindings($bindings), $e
    747▕             );
    748▕         }
    749▕     }

      +9 vendor frames 
  10  database/migrations/2022_04_19_024851_create.folders.php:22
      Illuminate\Support\Facades\Facade::__callStatic("create")

      +33 vendor frames 
  44  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

のようなエラーが出ました。

解決した方法

Schema::create('folders', function (Blueprint $table){
    $table->increments('id');
    $table->foreignId('user_id'); //外部キー制約 
    $table->string('title');
    $table->timestamps();
    });
 $table->foreign('user_id')->references('id')->on('users');

をこちらに変更しました。

$table->foreignId('user_id');

先輩エンジニアに聞いてみたらLaravelのバージョン9からできた書き方みたいです。

最後に

エラーが出てる状況は人それぞれ違うので上記のやり方で解消されない場合もあるのでご了承ください。

参考資料

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?