【问题标题】:Cannot add foreign key constrain on delete cascade无法在删除级联上添加外键约束
【发布时间】: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_attributes add constraint product_attributes_id_foreign foreign key (id) references products ( product_attribute_id) 删除级联)'

我在哪里做错了?

【问题讨论】:

  • product_product_attribute表中不应该设置外来逻辑吗?和你做product_id/pp_id一样吗? (没有 onDelete(cascade) 可以工作吗?)
  • 假设您有 productsproduct_attributesproduct_product_attribute 表。你想要,如果product 被删除,那么关联的product_attributesproduct_product_attribute 将被级联?请问products表的schema好吗?

标签: laravel laravel-7 laravel-migrations


【解决方案1】:

您正试图在product_attributes 表的主键和错误的引用列上添加外键引用。对products表的正确引用

$table->unsignedBigInteger('product_id');
$table->foreign('product_id')->references('id')
            ->on('products')->onDelete('cascade');

product_attributes 表的完整架构是

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->unsignedBigInteger('product_id');
        $table->foreign('product_id')->references('id')
            ->on('products')->onDelete('cascade');
        $table->timestamps();
    });

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 2014-01-17
    • 2011-02-24
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多