我正在尝试在 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 add foreign key constraint (SQL: alter table
产品变体订单add constraint
产品变体订单订单 ID 外国 foreign key (
order_id) references
orders (
id) on delete cascade)
⚠️编辑:这是我的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()
or unsignedBigInteger()
,这会让你以后不再头疼。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)