laravel - 如果分配了 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)
即使我有外键,如何删除记录?
解决方案
尝试改变这个
$table->foreign('parent_id')->references('id')->on('categories');
至
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
推荐阅读
- html - 背景图像完全停止加载
- javascript - 放大 Javascript 中的图标页面转换
- javascript - How to remove all classes from a menu except from the actual active element?
- networking - 如何在没有公共 IP 或堡垒主机的情况下 RDP 到我的 Azure VM
- java - 版本控制问题 Java
- matlab - 为什么 MATLAB 中的 pagemtimes 在 GPU 上运行缓慢?
- python - Flask 应用程序中的 ERR_TOO_MANY_REDIRECTS。在本地工作,但不在服务器中
- vba - 识别列、添加数量、删除重复项
- python - 如何使用 DRF 创建非常复杂的路线
- java - 尝试在 Android 中模糊图像的问题