[英]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]:一般错误:1215 无法添加外键约束(SQL:alter table posts
添加约束posts_category_id_foreign
外键( category_id
)在删除级联时引用categories
( id
))
在创建外键之前,类别需要存在,因为您不能将外键指向尚不存在的表。
Schema::create('categories', function (Blueprint $table) {
...
});
Schema::create('posts', function (Blueprint $table) {
...
});
其次,当您执行外键时,您必须将id
与表外键的类型相同。 当您执行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.