【问题标题】:Error in adding foreign key in laravellaravel 中添加外键出错
【发布时间】:2017-05-06 21:13:33
【问题描述】:

我是 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');
    });
}

cmets表迁移代码

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


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

【问题讨论】:

标签: laravel


【解决方案1】:

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

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

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

  3. 具有主键但后来在其他地方用作外键的表之前没有迁移。

无论哪种方式都尝试像这样将->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');
    });

}

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 2016-05-13
    • 2014-04-07
    • 2019-02-09
    相关资源
    最近更新 更多