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

新手上路,请多包涵

有人可以帮我解决这个问题吗?

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

原文由 Yrtymd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 380
2 个回答

在外键的情况下,引用字段和引用字段必须具有完全相同的数据类型。

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

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

原文由 Shadow 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 laravel 9 中,我在为我的帖子表创建外键时遇到了同样的错误

 SQLSTATE[HY000]: General error: 1005 Can't create table `wpclone`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_author_id_foreign` foreign key (`author_id`) references `users` (`id`) on delete restrict)

我的桌子看起来像这样:

     Schema::create('posts', function (Blueprint $table) {
                $table->id();
                $table->integer('author_id')->unsigned();
                $table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
                $table->string('title');
});

在我找到解决方案后,这种格式的 laravel 9 无符号修饰符运行良好

$table->unsignedBigInteger('author_id');

我的错误得到了解决。希望这会帮助你。谢谢

原文由 CodeWithVirag 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题