【问题标题】:LARAVEL 8: General error: 1005 occured while running migration with foreign keyLARAVEL 8:一般错误:使用外键运行迁移时发生 1005
【发布时间】:2021-02-19 18:43:09
【问题描述】:

我想运行一个名为 articles 的迁移,如下所示:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->id();
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->refrence('id')->on('users')->onDelete('cascade');
        $table->string('title');
        $table->string('slug');
        $table->text('body');
        $table->text('description');
        $table->text('body');
        $table->string('imageUrl');
        $table->string('tags');
        $table->integer('viewCount')->default(0);
        $table->integer('commentCount')->default(0);
        $table->timestamps();
    });
}

但我收到此错误:

SQLSTATE[HY000]: General error: 1005 Can't create table `gooyanet`.`#sql-1ce8_1d` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `articles` add constraint `articles_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

所以我在网上搜索,他们说我必须先创建表然后添加外键,所以我写了这个:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->string('slug');
        $table->text('description');
        $table->text('body');
        $table->string('imageUrl');
        $table->string('tags');
        $table->integer('viewCount')->default(0);
        $table->integer('commentCount')->default(0);
        $table->timestamps();
    });
    Schema::table('articles', function($table)
    {
        $table->foreign('user_id')
            ->references('id')->on('users')
            ->onDelete('cascade');
    });
}

但现在错误是这样的:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'gooyanet.articles' doesn't exist (SQL: alter table `articles` add constraint `articles_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

那么我应该怎么做才能使用外键运行此迁移?

【问题讨论】:

    标签: php mysql laravel migration laravel-8


    【解决方案1】:

    默认Laravel 8使用unsignedBigInteger作为外键:

    $table->bigInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    

    替代:Laravel 提供了额外的、更简洁的方法,这些方法使用约定来提供更好的开发者体验。上面的例子可以这样写:

    $table->foreignId('user_id')->constrained();
    

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 2021-06-18
      • 2013-12-07
      • 2015-04-09
      • 2020-03-19
      • 2019-11-21
      • 2017-01-31
      • 2013-12-30
      • 2021-03-29
      相关资源
      最近更新 更多