0
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 1 year has passed since last update.

【エラー解決】errno: 150 "Foreign key constraint is incorrectly formed"

Last updated at Posted at 2022-01-02

#errno: 150 "Foreign key constraint is incorrectly formed"について

php artisan migrate
上記コマンドを実施すると出現したので、解決した方法を記載していきます。

UsersテーブルとArticlesテーブルは1対多の関係

2021_〇〇_create_users_table.php
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }
2021_〇〇_create_articles_table.php
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->bigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

上記コードでphp artisan migrateを実施すると
General error: 1005 Can't create table n_sns.articles (errno: 150
"Foreign key constraint is incorrectly formed") (SQL: alter table articles add constraint articles_user_id_foreign foreign key (user_id) references users (id))
このようなエラーが出現。

2021_〇〇_articles_table.php側にコードを修正した事でエラー解消。

2021_〇〇_create_articles_table.php
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }
        $table->bigInteger('user_id');

ここのコードを

        $table->unsignedBigInteger('user_id');

こう書き換えました。

idカラムのデータ型は unsignedBigIntegerを選択するという事が分かりました。
符号なしBIGINTカラムと呼ばれており、マイナス部分がないBIGINTという意味だそうです。

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