在laravel中添加外键时出错

时间:2016-12-21 12:32:16

标签: laravel

我是laravel的初学者。我在laravel中添加外键时遇到问题。我试过但我找不到错误。

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table laravel_home1

#sql-4b8_2a (errno: 150 "Foreign key constraint is incorrectly formed")

(SQL: alter table `posts` add constraint
     `posts_comment_id_foreign` foreign key (`comment_id`) references
      `comments` (`id`))

发布表转移代码

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('content');       
        $table->integer('comment_id')->unsigned();
    });

    Schema::table('posts', function ($table) {
        $table->foreign('comment_id')
                ->references('id')
                ->on('comments');
    });
}

评论表迁移代码

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->string('comment');
        $table->timestamps();
    });
}


public function down()
{
    Schema::drop('comments');
}

1 个答案:

答案 0 :(得分:0)

在laravel中添加外键的问题有三个原因:

  1. 您已经完成了一些回滚或多次迁移同一个迁移文件,并将它们保存在缓存中,从而导致问题

  2. 您忘记将->unsigned();放在该索引的末尾。

  3. 以前不在其他位置用作主键的主键表不会先迁移。

  4. 无论哪种方式都尝试将->unsigned();放在最后,就像这样

    $table->integer('item_id')->unsigned();
    $table->foreign('item_id')->references('id')->on('items');
    

    然后运行composer dump-autoload

    然后php artisan migrate

    这应该有效!

    更新

    我发现迁移有什么问题:

    替换它:

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('content');       
            $table->integer('comment_id')->unsigned();
        });
    
        Schema::table('posts', function ($table) {
            $table->foreign('comment_id')
                    ->references('id')
                    ->on('comments');
        });
    }
    

    有了这个:

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('content');       
            $table->integer('comment_id')->unsigned();
    
            $table->foreign('comment_id')
                ->references('id')
                ->on('comments');
        });
    
    }