我在 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/