简体   繁体   English

如何在删除时处理 MySql + Laravel 中的外键约束?

[英]How can I deal with foreign key constraints in MySql + Laravel on delete?

I have a slots table that looks something like this.我有一个看起来像这样的插槽表。 Overly simplified, but it helps for demonstration:过于简化,但有助于演示:

Date日期 Service_id服务标识
2021-11-03 2021-11-03 1 1
2021-11-04 2021-11-04 2 2

Basically, a user picks a date and the service he wants.基本上,用户选择一个日期和他想要的服务。 This is a booking system.这是一个预订系统。 There is also a foreign key relationship from service_id above to the id of the services table.从上面的 service_id 到services表的 id 还有一个外键关系。

id ID name姓名
1 1 Haircut理发
2 2 Manicure修指甲
3 3 Massage按摩

My migration for the slots table contains the following:我对插槽表的迁移包含以下内容:

Schema::table('slots', function (Blueprint $table) {
     $table->foreignId('service_id')->nullable()->constrained();
});

What I want to do now is to be able to delete a service without having any errors being thrown from existing records in the slots table.我现在想要做的是能够删除服务,而不会从插槽表中的现有记录中抛出任何错误。

you can$table->nullOnDelete();你可以$table->nullOnDelete(); but this way the column Service_id in slots table should be nullable:但是这样,槽表中的 Service_id 列应该可以为空:

Schema::table('slots', function (Blueprint $table) {
     $table->foreignId('service_id')->nullable()->constrained()->nullOnDelete();
});

this way, the corresponding row in slots will have null in Service_id column.这样,插槽中的相应行将在Service_id列中具有 null。

the other way is to use ->cascadeOnDelete() , this way, when you delete a service, all related slots will be deleted:另一种方法是使用->cascadeOnDelete() ,这样当你删除一个服务时,所有相关的槽都会被删除:

 Schema::table('slots', function (Blueprint $table) {
         $table->foreignId('service_id')->nullable()->constrained()->cascadeOnDelete();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM