简体   繁体   English

无法添加外键约束

[英]Cannot add foreign key constraint

    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]: General error: 1215 Cannot add foreign key constraint (SQL: alter table posts add constraint posts_category_id_foreign foreign key ( category_id ) references categories ( id ) on delete cascade) ----> SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table posts添加约束posts_category_id_foreign外键( category_id )在删除级联时引用categoriesid ))

Categories needs to exist before the foreign key is created, as you can not foreign key to a table that does not exists yet.在创建外键之前,类别需要存在,因为您不能将外键指向尚不存在的表。

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

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

Secondly when you do a foreign key, you will have to have the id as the same type as the tables foreign key.其次,当您执行外键时,您必须将id与表外键的类型相同。 When you do increments('id') it will actually create an unsigned integer, therefor your category_id in posts should be an unsigned integer.当您执行increments('id')时,它实际上会创建一个未签名的 integer,因此您在帖子中的category_id应该是一个未签名的 integer。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM