我尝试进行laravel迁移,但遇到此错误
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `urbancruise`.`#sql-18f8_112` (errno: 150 "Foreign key cons
traint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_category_id_foreign` foreign key (`c
ategory_id`) references `categories` (`id`))
这是我的代码
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down(){
Schema::drop('categories');
}
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}
public function down(){
Schema::drop('posts');
}
答案 0 :(得分:2)
创建外键时,categories.id
和posts.category_id
必须具有相同的类型。
将->bigInteger()
替换为->integer()
应该可以解决您的问题:
您的类别迁移:
public function up(){
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down(){
Schema::drop('categories');
}
在您的信息迁移中:
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id', false, true);
//Or $table->unsignedInteger('category_id');
$table->foreign('category_id')
->references('id')
->on('categories');
$table->timestamps();
});
}
public function down(){
Schema::drop('posts');
}
希望有帮助。
答案 1 :(得分:1)
在子表和父表中,外键应始终为同一类型。
在您的情况下,categories.id
的类型为ٰ INTEGER,而posts.category_id
的类型定义为BIGINT。用下面的方法替换您的posts
迁移应该可以。
public function up() {
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}