【发布时间】:2019-07-27 15:40:55
【问题描述】:
当我尝试在 laravel 中运行迁移命令时出现此错误
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `posts` add constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
在将此问题标记为重复或否决之前,请阅读 完整的问题。
我在这个网站上找到的解决方案是:
- 标记为
unsigned我知道了 - 在 2 步中生成整数 我有这个
- 架构顺序问题我提供了屏幕截图以查看情况并非如此
我不知道为什么会出现这个错误,这是我的代码:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug')->unique();
$table->longText('body');
$table->string('photo');
$table->text('meta_description')->nullable();
$table->text('meta_tags')->nullable();
$table->integer('user_id')->unsigned();
$table->string('publish')->default('0');
$table->string('comment')->default('0');
$table->timestamps();
});
Schema::table('posts', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
有什么想法吗?
更新
用户架构
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('photo')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
【问题讨论】:
-
请发布
users表的迁移文件 -
@AhmedNourJamalEl-Din 更新
-
请尝试将外键更改为
bigInteger,如下所示:$table->bigInteger('user_id')->unsigned(); -
@AhmedNourJamalEl-Din 很奇怪!它现在可以工作了:) 谢谢
-
很高兴它成功了^^。我回答了它,以便人们可以得到一些帮助