【发布时间】:2020-09-01 04:06:49
【问题描述】:
我正在尝试在两个迁移上创建级联:
Schema::create('product_product_attribute',
function ($table) {
$table->bigIncrements('id');
$table->bigInteger('product_id')->unsigned();
$table->bigInteger('product_attribute_id')->unsigned();
$table->boolean('custom')->nullable();
$table->string('title')->nullable();
$table->string('unit')->nullable();
$table->string('type')->nullable();
$table->text('value')->nullable();
$table->float('price')->nullable();
$table->bigInteger('position')->nullable();
$table->foreign('product_id', 'pp_id')->references('id')
->on('products')->onDelete('cascade');
$table->timestamps();
});
Schema::create('product_attributes', function ($table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('unit')->nullable();
$table->string('type');
$table->float('price')->nullable();
$table->nestedSet();
$table->foreign('id')->references('product_attribute_id')
->on('products')->onDelete('cascade');
$table->timestamps();
});
那么它应该做什么:
如果产品包含属性,则属性和属性的数据透视表都应该是级联的。
这失败了:
Illuminate/Database/QueryException with message 'SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
product_attributesadd constraintproduct_attributes_id_foreignforeign key (id) referencesproducts(product_attribute_id) 删除级联)'
我在哪里做错了?
【问题讨论】:
-
product_product_attribute表中不应该设置外来逻辑吗?和你做product_id/pp_id一样吗? (没有 onDelete(cascade) 可以工作吗?)
-
假设您有
products、product_attributes、product_product_attribute表。你想要,如果product被删除,那么关联的product_attributes和product_product_attribute将被级联?请问products表的schema好吗?
标签: laravel laravel-7 laravel-migrations