我正在尝试在 Laravel 8 上创建迁移,这是我的表格
class CreateProductVariationOrderTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_variation_order', function (Blueprint $table) {
$table->integer('order_id')->unsigned()->index();
$table->integer('product_variation_id')->unsigned()->index();
$table->integer('quantity')->unsigned();
$table->timestamps();
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->foreign('product_variation_id')->references('id')->on('product_variations')->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('product_variation_order');
}
}
当我运行 php artisan migrate
时,我收到了这样的错误:SQLSTATE[HY000]: General error: 1215 Cannot addforeign keyconstraint (SQL: alter table
Product_variation_order添加约束
product_variation_order_order_id_foreign外键(
order_id)引用
orders(
id)删除级联)
⚠️编辑:这是我的product_variation
迁移文件。
class CreateProductVariationsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_variations', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned()->index();
$table->string('name');
$table->integer('price')->nullable();
$table->integer('order')->nullable();
$table->timestamps();
$table->foreign('product_id')->references('id')->on('products');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('product_variations');
}
}
最佳答案
外键必须与引用键类型相同。
在订单表中,您将 id 定义为 bigIncrements()
,它是无符号大整数。
在您的product_variation_order表中,您将order_id定义为无符号整数。
所以这两个键不匹配。一般来说,您应该使用大整数,因为它允许您的数据库变得更大,并且整数和大整数之间的空间差异并不显着。
因此将 order_id
更改为无符号大整数。
$table->unsignedBigInteger('order_id')->nullable();
此外,为了保持一致性,所有键都应该是 bigIncrements()
或 unsignedBigInteger()
,这将让您以后不再头疼。
关于php - Laravel 8 迁移 "General error: 1215 Cannot add foreign key constraint",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66736682/