我有一个表Customers with Cars, Cars with Services。当我删除汽车时,我也想从数据库中删除服务当我删除Customer时,我希望能够删除Customer,它的Cars,它的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)
}
我已经尝试了我在StackOverflow和文档中看到的大部分内容,但到目前为止似乎没有任何工作。
在阅读了文档和一堆StackOverflow答案后,没有什么对我真正有效。文档和/或StackOverflow建议我在迁移模型时添加约束,或/并将约束添加到结构体gorm:"constraint:OnDelete:CASCADE;"
,我也尝试了db.Select("cars").Delete(&customers)
,但没有成功。这就是我的做法,不确定这是否是最佳实践,但它从数据库中删除了相关记录。我这样更新了deleteccustomer和deleteCar端点:
//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
var cars []Car
db.First(&customer, params["id"])
db.Model(&customer).Related(&cars)
deleteServicesSqlStatement := `
DELETE FROM services
WHERE car_id = $1;`
for i, car := range cars {
fmt.Println(i, car.ID)
err := db.Exec(deleteServicesSqlStatement, car.ID).Error
if err != nil {
fmt.Println(err)
}
}
DeleteCarsSqlStatement := `
DELETE FROM cars
WHERE customer_id = $1;`
err := db.Exec(DeleteCarsSqlStatement, params["id"]).Error
if err != nil {
fmt.Println(err)
}
db.Debug().Unscoped().Delete(&customer)
json.NewEncoder(w).Encode(&customer)
}
//delete car
func deleteCar(w http.ResponseWriter, r *http.Request) {
//handle CORS
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
params := mux.Vars(r)
var car Car
db.First(&car, params["id"])
sqlStatement := `
DELETE FROM services
WHERE car_id = $1;`
err := db.Exec(sqlStatement, params["id"]).Error
if err != nil {
fmt.Println(err)
}
db.Debug().Unscoped().Delete(&car)
json.NewEncoder(w).Encode(&car)
}