【发布时间】:2021-06-18 13:04:46
【问题描述】:
我正在尝试在 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 product_variation_orderadd constraintproduct_variation_order_order_id_foreign 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类型是整数吗?
-
您可以发布您的
product_variations迁移吗?外键和它们引用的列必须是完全相同的类型 -
@brombeer 是的,只是在下面添加了它
-
抱歉,请迁移您的
orders表。尝试创建外键时,orders和product_variations表是否存在? -
@brombeer 我可以留给你我的 github 仓库:github.com/rust-7/fore-api 我所有的迁移都在
app > database > migrations,我认为这样更好,因为迁移太多了
标签: php laravel migration database-migration laravel-8