【发布时间】:2021-05-07 13:46:42
【问题描述】:
我有一个类别表,允许通过 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)
即使我有外键,如何删除记录?
【问题讨论】:
-
在此处添加
onDelete('cascade')$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade'); -
我放 onDelete('cascade) 的问题是它也删除了它的父类,我只想删除子类(子类)。
-
onDelete('cascade')不删除parent,如果parent已经删除则删除child。 -
如果我删除具有 parent_id 的子类别,它会自动删除父(类别)。为什么会这样?我不明白...
标签: laravel