php - laravel errno 150 外键约束格式不正确

标签 php mysql laravel-5

谁能帮我解决这个问题?

有 3 个表有 2 个外键:

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")

最佳答案

如果是外键,引用字段和引用字段必须具有完全相同的数据类型。

您将usersfirms 中的id 字段创建为有符号 整数。但是,您将两个外键创建为无符号整数,因此创建键失败。

您需要将 unsigned 子句添加到 id 字段定义中,或者从外键字段中删除 unsigned 子句。

关于php - laravel errno 150 外键约束格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40863517/

相关文章:

php - Laravel 中 BelongsTo 和 HasOne 有什么区别

PHPUnit:强制显示断言值

php - 将 HTML5 Canvas 保存为单色 bmp

mysql - 如何撤销sql USE?

mysql - SQL Server Migration Assistant (SSMA) - 它会删除源数据吗?

php - Mysql加入多于2个表

php - Laravel 5.2 的软删除级联

php - 使用动态生成的表单更新记录

php - 如何在 Laravel 5 表单中使用 Markdown 作为文本区域输入字段?

php - MySQL 中的双引号 (Laravel Seeder)