首页 > 解决方案 > 如果分配了 parent_id,如何删除记录?

问题描述

我有一个类别表,允许通过 parent_id 拥有子类别。

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();

            $table->string('name');
            $table->unsignedBigInteger('parent_id')->unsigned()->nullable();
            $table->string('slug');

            $table->foreign('parent_id')->references('id')->on('categories');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

当我想删除一个子类别时,问题就来了。当我有外键时出现错误。

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`doogmas`.`categories`, CONSTRAINT `categories_parent_id_foreign` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`)) (SQL: delete from `categories` where `id` = 30)

即使我有外键,如何删除记录?

标签: laravel

解决方案


尝试改变这个

$table->foreign('parent_id')->references('id')->on('categories');

$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');

推荐阅读