【问题标题】:Cannot add foreign key constraint无法添加外键约束
【发布时间】:2020-09-26 20:24:48
【问题描述】:
    Schema::create('posts', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title');
                $table->text('body');
                $table->string('image')->nullable();
                $table->integer('user_id')->unsigned();
                $table->integer('category_id');
                $table->timestamps();

                $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            });

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();    
        });

----> SQLSTATE [HY000]:一般错误:1215 无法添加外键约束(SQL:alter table posts 添加约束posts_category_id_foreign 外键(category_id)在删除级联时引用categoriesid))

【问题讨论】:

  • 它们是按顺序创建的,所以是先创建帖子,然后是类别,应该切换顺序,或者在底部迁移中添加约束
  • 我的回答对您有帮助吗?还是您对问题仍有疑问?

标签: php laravel


【解决方案1】:

类别需要在创建外键之前存在,因为您不能对尚不存在的表进行外键。

Schema::create('categories', function (Blueprint $table) {
    ...
});

Schema::create('posts', function (Blueprint $table) {
    ...
});

其次,当您使用外键时,您必须将id 与表外键的类型相同。当您执行increments('id') 时,它实际上会创建一个无符号整数,因此您在帖子中的category_id 应该是一个无符号整数。

Schema::create('posts', function (Blueprint $table) {
    $table->unsignedInteger('category_id');

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

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 2017-07-16
    • 2013-03-10
    • 2021-11-05
    • 2018-02-13
    • 2018-05-16
    相关资源
    最近更新 更多