Reputation: 318
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.
Upvotes: 0
Views: 183
Reputation: 12208
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();
});
Upvotes: 1