I have a table Customers with Cars, and Cars has Services. When I delete the Car I also want to delete the Services from the database And when I delete the Customer I want to be able to delete Customer, its Cars, Its Services.
I tried the following to delete Car and Services related to the Car, but it only deletes the Car from the database, how do I delete both Cars and its Services?
type Customer struct {
gorm.Model
FirstName string
LastName string
Phone string `gorm:"typevarchar(100);unique_index"`
Cars []Car `gorm:"constraint:OnDelete:CASCADE;"`
}
type Car struct {
gorm.Model
Make string
Modelo string
Color string
VinNumber string `gorm:"typevarchar(100);unique_index"`
Services []*Service `gorm:"constraint:OnDelete:CASCADE;"`
CustomerId int
}
type Service struct {
gorm.Model
Comment string
Miles string
CarId int
}
//endpoints
//delete customer
func deleteCustomer(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
var customer Customer
db.First(&customer, params["id"])
db.Unscoped().Delete(&customer)
json.NewEncoder(w).Encode(&customer)
}
func deleteCar(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
params := mux.Vars(r)
var car Car
db.First(&car, params["id"])
db.Select("Services").Unscoped().Delete(&car)
json.NewEncoder(w).Encode(&car)
}
I already tried most of what I seen in StackOverflow and the docs but nothing seems to work so far.