Laravel onDelete('cascade') 不起作用
Laravel onDelete('cascade') does not work
我的表格:
Schema::create('support_categories', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->nullable();
$table->timestamps();
});
Schema::create('supports', function (Blueprint $table) {
$table->id();
$table->foreignId('support_category_id')->onDelete('cascade')->constrained('support_categories')->nullable();
$table->string('title');
$table->string('slug');
$table->timestamps();
});
当我尝试删除 support_categories
时出现以下错误
Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
你只是把外键写错了。
而不是:
$table->foreignId('support_category_id')->onDelete('cascade')->constrained('support_categories')->nullable();
写:
$table->foreignId('support_category_id')->nullable()->constrained('support_categories')->onDelete('cascade');
或者您可以使用 casadeOnDelete():
$table->foreignId('support_category_id')->nullable()->constrained('support_categories')->casadeOnDelete();
我的表格:
Schema::create('support_categories', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->nullable();
$table->timestamps();
});
Schema::create('supports', function (Blueprint $table) {
$table->id();
$table->foreignId('support_category_id')->onDelete('cascade')->constrained('support_categories')->nullable();
$table->string('title');
$table->string('slug');
$table->timestamps();
});
当我尝试删除 support_categories
时出现以下错误Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
你只是把外键写错了。
而不是:
$table->foreignId('support_category_id')->onDelete('cascade')->constrained('support_categories')->nullable();
写:
$table->foreignId('support_category_id')->nullable()->constrained('support_categories')->onDelete('cascade');
或者您可以使用 casadeOnDelete():
$table->foreignId('support_category_id')->nullable()->constrained('support_categories')->casadeOnDelete();