2

嘿,我目前正在进行 Laravel 6 数据库迁移,但是当我执行 php artisan migrate:fresh 时,以下错误跳到我身上: SQLSTATE [HY000]:一般错误:1215 无法添加外键约束(SQL:alter table category_postadd constraint category_post_category_id_foreignforeign key ( category_id) 参考id( categories) 在更新级联上删除级联)

我检查了以下内容:

  • 错别字
  • 引用顺序错误
  • 自 Laravel 5.8 起从增量更改为大增量
  • 错误类型

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

        // 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 有很好的了解,所以如果您能解释我做错了什么,那就太好了:)

4

1 回答 1

4

根据文档bigIncrements代表:

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

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

于 2019-09-12T08:10:23.797 回答