简体   繁体   中英

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 1
2021-11-04 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.

id name
1 Haircut
2 Manicure
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(); but this way the column Service_id in slots table should be nullable:

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.

the other way is to use ->cascadeOnDelete() , this way, when you delete a service, all related slots will be deleted:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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