3
0

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 3 years have passed since last update.

【Laravel】外部キーを設定するにはデータ型を揃えること

Last updated at Posted at 2020-12-19

【Laravel】外部キーを設定するにはデータ型を揃えること

使用環境

  • windows10
  • XAMPP 7.3.18
  • Laravel 6.*

背景

Laravelでテーブルを作成し、外部キーを設定しようとしているのにエラーが発生する。

エラー内容

image.png

SQLSTATE[HY000]: General error: 1005 Can't create table 'hoge'.'hoge'(errno:150 "Foreign key constraint is incorrectly formed")")

原因

今回の原因はデータ型が適切でないことだった。
【Laravel】migrate時の「Foreign key constraint is incorrectly formed」エラーの解消方法

対処法

参照先$table->increments('id')のとき、参照先カラムのデータ型が符号なしの整数型だったため、外部キーを設定するカラムも符号なしの整数型$table->unsignedInteger('user_id')で指定する必要があるらしい。

データ型を適切に指定し、php artisan migrate:refreshでテーブルをすべて作り直し解決!

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?