laravel errno 150 外部キー制約が正しく形成されていません 質問する

laravel errno 150 外部キー制約が正しく形成されていません 質問する

誰かこの問題を解決するのを手伝ってくれませんか?

2 つの外部キーを持つ 3 つのテーブルがあります。

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

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

Schema::create('jobs', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title')->nullable();
    $table->integer('firm_id')->unsigned()->nullable();
    $table->foreign('firm_id')->references('id')->on('firms');
    $table->timestamps();
});
                    

移行実行後のエラー:

[Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
   (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter ta
  ble `firms` add constraint `firms_user_id_foreign` foreign key (`user_id`)
  references `users` (`id`))

  [PDOException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
   (errno: 150 "Foreign key constraint is incorrectly formed")

ベストアンサー1

外部キーの場合、参照先フィールドと参照元フィールドのデータ型はまったく同じである必要があります。

idの両方にフィー​​ルドを作成します。usersfirms署名済み整数。ただし、両方の外部キーを次のように作成します。署名なし整数であるため、キーの作成は失敗します。

unsignedフィールド定義に句を追加するかidunsigned外部キー フィールドから句を削除する必要があります。

おすすめ記事