laravel migration“ SQL:更改表`posts”添加约束`posts_category_id_foreign`外键(`category_id`)引用`categories`(`id`)”

时间:2019-07-09 20:39:54

标签: laravel laravel-5 eloquent

我尝试进行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');
}

2 个答案:

答案 0 :(得分:2)

创建外键时,categories.idposts.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();
    });
}