Laravel 6:SQLSTATE [HY000]:一般错误:1215无法添加外键约束

时间:2019-09-12 08:02:28

标签: php mysql sql laravel-6

嘿,我目前正在Laravel 6数据库迁移中工作,但是当我执行php artisan migration:fresh时,以下错误提示我: SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:更改表category_post添加约束category_post_category_id_foreign外键(category_id)引用idcategories)在更新级联上删除级联上)

我检查了以下内容:

  • 错别字
  • 引用顺序错误
  • 从Laravel 5.8开始,从增量更改为bigIncrement
  • 类型错误

这是我的迁移代码,希望您能看到我犯的错误,因为我找不到它。

        // Table for storing Blog Posts
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->string('read_time');
            $table->string('summary');
            $table->string('body');
            /*$table->timestamps('created_at');
            $table->timestamps('updated_at');*/
            $table->timestamps();
        });

        // Table for storing categories
        Schema::create('categories', function (Blueprint $table) {
          $table->bigIncrements('id');
          $table->string('name')->unique();
          $table->string('slug')->unique();
          $table->string('description');
          $table->timestamps();
        });

        // Table for association of Categories with Blog Posts
        Schema::create('category_post', function (Blueprint $table) {
          $table->bigInteger('category_id');
          $table->bigInteger('post_id');

          $table->foreign('category_id')->references('id')->on('categories')
            ->onUpdate('cascade')->onDelete('cascade');
          $table->foreign('post_id')->references('id')->on('posts')
            ->onUpdate('cascade')->onDelete('cascade');

          $table->primary(['post_id', 'category_id']);
        });

        // Table for association of Users with Blog Posts
        Schema::create('user_post', function (Blueprint $table) {
          $table->bigInteger('user_id');
          $table->bigInteger('post_id');

          $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
          $table->foreign('post_id')->references('id')->on('posts')
            ->onUpdate('cascade')->onDelete('cascade');

          $table->primary(['user_id', 'post_id']);
        });

毕竟,目标是将类别和用户与帖子相关联,以便我可以在帖子上包含标签和用户。

在此先感谢您的帮助和友善,我对Laravel还是很陌生,但是我对PHP有很好的了解,因此,如果您能解释我做错了什么,那将是非常不错的:)

1 个答案:

答案 0 :(得分:3)

根据documentationbigIncrements表示:

  

自动递增UNSIGNED BIGINT(主键)等效列。

因此,您的外键需要匹配(unsignedBigInteger())。