【问题标题】:Foreign key constraint is incorrectly formed - Laravel外键约束格式不正确 - Laravel
【发布时间】:2019-07-25 06:48:31
【问题描述】:

我在 XAMPP 堆栈上使用 Laravel 5.8。


考虑这两个迁移来创建两个表:

post_categories 表。

Schema::create('post_categories', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('name');
  $table->string('slug');
  $table->string('status');
  $table->timestamps();
});

帖子表。

Schema::create('posts', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('name');
  $table->string('slug');
  $table->mediumText('description');
  $table->integer('views');
  $table->integer('post_category_id')->unsigned();
  $table->integer('user_id')->unsigned();
  $table->timestamps();

  $table->foreign('post_category_id')->references('id')->on('post_categories');
});

当我运行 php artisan migrate 时,我收到以下错误:

一般错误:1005 无法创建表testdb.#sql-38d8_102(错误号:150“外键约束格式不正确”)。


我都试过了:

  • php artisan migrate
  • php artisan migrate:fresh

我还尝试将post_category_id 字段更改为常规整数,而不是无符号:没有区别。

还重启了MySQL服务器和Apache服务,没有什么影响。

post_categories 迁移posts 迁移之前运行。 posts 表已创建,但外键未创建。


为什么会抛出这个错误,我该如何解决?

【问题讨论】:

  • 检查您的迁移顺序。在这种情况下,“post_categories”应该放在“posts”之前……最后尝试在下一次迁移中添加外键,同时保持引用的 id 类型相同……
  • 我的评论与您的​​问题无关,但您在迁移时忘记引用user_id FK
  • @LucasPiazzi,是的,我已经添加了,谢谢。

标签: php mysql laravel


【解决方案1】:

这可能是因为您试图创建一个带有整数字段的外键到一个大整数字段。在您的帖子迁移中,而不是这个

$table->integer('post_category_id')->unsigned();

这样做:

$table->bigInteger('post_category_id')->unsigned();

【讨论】:

  • 这解决了,我什至没有注意到 bigIncrements 字段。无论如何,它曾经只是旧 Laravel 版本的增量,谢谢!
【解决方案2】:

而不是这个:

$table->integer('post_category_id')->unsigned();

试试这个:

$table->unsignedBigInteger('post_category_id');

【讨论】:

    【解决方案3】:

    我想链接两个表,用户表和存款表时遇到了同样的错误。我尝试了很多选择,但没有奏效。但是,这对我来说是创建存款迁移的方法:

    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    
    

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 2017-10-04
      • 2018-02-19
      • 2021-05-26
      • 2017-04-13
      • 2019-09-17
      • 2020-09-24
      • 2019-11-02
      • 2023-03-19
      相关资源
      最近更新 更多