php - 外键约束的格式不正确 - Laravel

标签 php mysql laravel

我在 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 时,出现以下错误:

General error: 1005 Can't create table testdb.#sql-38d8_102 (errno: 150 "Foreign key constraint is incorrectly formed").


我试过同时运行:

  • php artisan migrate
  • php artisan migrate:fresh

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

还重新启动了 MySQL 服务器和 Apache 服务,没有什么不同。

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


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

最佳答案

发生这种情况的原因可能是您试图创建一个外键,该外键包含一个整数字段到一个大整数字段。在您的帖子迁移中,而不是这个

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

这样做:

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

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

相关文章:

php - Solr/lucene 搜索 - 有多好用 - 哪一个?

mysql - 如何使用 csv 文件更新数据库中的特定行?(rails)

mysql - sql中计数不为空

php - SQL 关闭运算符

php - 使用 flashvars 将 php 变量发送到 flash

mysql - 如何将字段从时间戳转换为日期时间

php - 查询 : return all rows even if the count of the associated rows are 0

php - Laravel 419 错误 - VerifyCsrfToken 问题

php - Laravel 4 中未加载自定义验证类

PHP改进数据检索