【发布时间】: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 migratephp artisan migrate:fresh
我还尝试将post_category_id 字段更改为常规整数,而不是无符号:没有区别。
还重启了MySQL服务器和Apache服务,没有什么影响。
post_categories 迁移在posts 迁移之前运行。 posts 表已创建,但外键未创建。
为什么会抛出这个错误,我该如何解决?
【问题讨论】:
-
检查您的迁移顺序。在这种情况下,“post_categories”应该放在“posts”之前……最后尝试在下一次迁移中添加外键,同时保持引用的 id 类型相同……
-
我的评论与您的问题无关,但您在迁移时忘记引用
user_idFK -
@LucasPiazzi,是的,我已经添加了,谢谢。