无法在删除级联上添加外键约束

Cannot add foreign key constrain on delete cascade

我正在尝试在两个迁移上创建级联:


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();
});

那么它应该做什么:

如果包含属性的产品,属性和属性的主元 table 应该是级联的。

这失败了:

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) on delete cascade)'

我哪里做错了?

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

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

product_attributes table 的完整架构是

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();
    });