我使用MYSQL v5.7和Laravel v5.6,我在产品表上添加了外键。
但是得到这样的错误。
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `product` add constraint `product_category_id_foreign` foreign key (`category_id`) references `category` (`id`) on delete cascade)
这是我的产品表
public function up()
{
Schema::create('product', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned()->nullable();
$table->integer('admin_id')->unsigned()->nullable();
$table->string('name');
$table->string('description');
$table->integer('price');
$table->binary('image')->nullable(false)->change();
$table->timestamps();
});
Schema::table('product', function($table){
$table->foreign('category_id')->references('id')->on('category')->onDelete('cascade');
$table->foreign('admin_id')->references('id')->on('admin')->onDelete('cascade');
});
}
这是我的类别表
public function up()
{
Schema::create('category', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
这里有什么问题?
答案 0 :(得分:0)
一个可能的问题是product.category_id
(外键列)和category.id
(引用的主键)之间的数据类型不同。
(这只是一种可能性。问题可能是由于其他原因造成的。)
但我们首先要检查两列的数据类型是否与完全匹配。如果它们不匹配,那么我们就无法定义InnoDB外键约束。
我的猜测是category.id
被定义为BIGINT
数据类型。
(我猜,我不是Laravel模式构建器的专家,但我确实看到模式构建器完成了掩盖/隐藏MySQL表的实际SQL定义的重要工作。)< / p>
(并不清楚为什么Laravel需要指定外键列的数据类型。我们知道它与引用列的数据类型匹配。)
我对修复的猜测是改变这一行
来自:
$table->integer('category_id')->unsigned()->nullable();
为:
$table->bigInteger('category_id')->nullable();