当我尝试在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
我知道了 我不确定为什么会收到该错误,这是我的代码:
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();
});
答案 0 :(得分:2)
users
表中的主键是BigIncrements
,它创建了一个无符号的大整数列,但是posts
表中的外键是整数,因此它们不是同一类型。 / p>
将外键更改为bigInteger
将对其进行修复。
所以这个:
$table->bigInteger('user_id')->unsigned();
代替:
$table->integer('user_id')->unsigned();
答案 1 :(得分: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->bigInteger('user_id')->unsigned();
$table->string('publish')->default('0');
$table->string('comment')->default('0');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});